Java Very Simple Solution :)


  • 2
    public int climbStairs(int n) {
        int a = 0, b = 1, temp = 0;
        for(int i = 0; i < n; i++) {
            temp = b; 
            b = b + a; 
            a = temp;
        }
        return (n > 0) ? b : 0;
    }

  • 2

    Logic here is to just keep track of distinct ways to reach previous two steps. :)


  • 0
    W

    I just can't understand, can you explain it to me ?Thank you!!


  • 0
    N

    For any state, you just need to look at the two previous steps. To reach step n, you can take 1 step from (n - 1), or 2 steps from (n - 2).

    ways[n] = ways[n - 1] + ways[n - 2]


Log in to reply
 

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