Fibonacci sequence solution in Java


  • 12
    Y

    public class Solution {

    public int climbStairs(int n) {
        if(n < 0)
            return 0;
        if(n == 1)
            return 1;
            
        int[] store = new int[n];
        
        store[0] = 1;
        store[1] = 2;
        
        for(int i = 2; i < n; ++i)
            store[i] = store[i-1] + store[i-2];
            
        return store[n-1];
    }
    

    }


  • 3
    F

    This has space complexity O(n). You don't need to create an array of n elements since you always need the last two at each iteration.


  • 0
    2

    @FabrizioDemaria do you mean to create an array of size 2?


  • 0
    A

    class Solution {
    public int climbStairs(int n) {
    int count=0;
    if(n==0 )
    {
    count=0;
    return count;
    }
    if(n==1|| n <0)
    {
    count=1;
    return count;
    }
    if(n==2)
    {
    count=2;
    return count;
    }

    int a = 1;
    int b = 2;
    int c=0;

     while( n-- > 2)
     {
         c=a+b;
         a=b;
         b=c;
         
     }
        return c;
    }
    

    }


  • 0
    A

    @20170601 i posted a code which will reduce your space complexity.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.