C++ 0ms O(n) time, O(1) space solution (Iterative)


  • 1
    B

    Iterate from 3 to n. In each iteration, count[iter] = count[iter-1] + count[iter-2] (i.e. number of ways to get to n = ways(n-1) + ways(n-2)).

    int climbStairs(int n) {
            if (n <= 3) return n;
            int curr = 4, step1 = 3, step2 = 2, count;
            while(curr <= n) {
                count = step1 + step2;
                step2 = step1;
                step1 = count;
                curr++;
            }
            return count;
        }
    

  • 0
    H

    My solution is just like yours but only beats 8.6% of cpp submissions :(


Log in to reply
 

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