Counting Ways to Climb Stairs
Problem
You are climbing a staircase of n steps. At each move you can ascend either one or two steps. Count the number of distinct sequences that reach the top.
Input
n = 5Output
8Recurrence: dp[i] = dp[i−1] + dp[i−2].
def climb_stairs(n):
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
function climbStairs(n) {
const dp = new Array(n + 1);
dp[0] = 1;
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
if (n >= 1) dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
int climbStairs(int n) {
vector<int> dp(n + 1, 0);
dp[0] = 1;
if (n >= 1) dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}