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(n)Code C++, Python and C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

The last move onto step i was either a single step from i-1 or a double step from i-2. So the number of ways to reach i is the sum of the ways to reach those two.

Code

int climbStairs(int n) {
    vector<int> dp(n + 1);
    dp[0] = dp[1] = 1;
    for (int i = 2; i <= n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}
def climb_stairs(n: int) -> int:
    dp = [0] * (n + 1)
    dp[0] = dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]
public static int ClimbStairs(int n) {
    var dp = new int[n + 1];
    dp[0] = dp[1] = 1;
    for (int i = 2; i <= n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

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.