Climbing stairs

Count the ways to climb n steps taking 1 or 2 at a time. The gentlest introduction to DP.

Time O(n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

The last move onto step i was either a single step from i-1 or a double step from i-2. So ways(i) = ways(i-1) + ways(i-2). Only the last two values are ever read, so two variables replace the whole table.

Code

public static int ClimbStairs(int n) {
    int prev2 = 1, prev1 = 1;
    for (int i = 2; i <= n; i++) {
        int cur = prev1 + prev2;
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
static int climbStairs(int n) {
    int prev2 = 1, prev1 = 1;
    for (int i = 2; i <= n; i++) {
        int cur = prev1 + prev2;
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
int climbStairs(int n) {
    int prev2 = 1, prev1 = 1;
    for (int i = 2; i <= n; i++) {
        int cur = prev1 + prev2;
        prev2 = prev1; prev1 = cur;
    }
    return prev1;
}
def climb_stairs(n: int) -> int:
    prev2, prev1 = 1, 1
    for i in range(2, n + 1):
        cur = prev1 + prev2
        prev2, prev1 = prev1, cur
    return prev1

Tips

In the .NET library

int overflows silently at n = 46 here. Use long, or wrap the sum in checked(...) to get an OverflowException instead of a wrong answer.