Climbing stairs
Count the ways to climb n steps taking 1 or 2 at a time. The gentlest introduction to DP.
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 prev1Tips
- Define the state (ways to reach step i), the transition, and the base cases. Every DP problem has those three parts.
- Start with the table version dp[i] = dp[i-1] + dp[i-2] when you first meet a problem like this; then notice which cells you read and shrink it.
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.