[JAVA] 0m, 7 Lines DP Solution. Clear and Easy


  • 0
    Y

    Basically it's Fibonacci Numbers, so:

    public int climbStairs(int n) {
        int a = 1;
        int b = 1;
        if(n<2) return a;// n=0 or n=1
        for(int i = 2;i<n+1;i++){//n>1
            a=a+b;
            b=a-b;
        }
        return a;
    }

  • 0
    Z

    Can you explain these two lines in for loop?
    a=a+b;
    b=a-b;


  • 1
    Y

    @zfrancica
    these two lines are to calculate the Fibonacci Numbers one by one. a&b point to two adjacent values.
    a begin with 1 , then pointers move right,
    "new"a ="old" a+"old"b=2, a gets new value
    b moving right , get the old value of a,

    so "new"b = "old" a = "new"a-"old"b

    a=a+b;
    b=a-b;


Log in to reply
 

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