Dynamic Programming - Example
Leetcoce 70 Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Constraints:
1 <= n <= 45
Analysis:
Think about this question, when n = 10, how many ways to finish the 10th step?
Ahh, not easy to count directly, but if we know the number of ways to finish the 9th step and 8th step, then we should know the number of ways to finish the 10th step (This is recursion!!!), which is the sum of them.
Why sum?
Because these are the only two different ways for the last climb to finish the 10th step, one is 1 step from the 9th, the other is 2 steps from the 8th.
To generalize the question, how about to the nth step?
If we define the number of ways to finish the nth step as f(n), then the number of ways for (n-1)th is f(n-1), for (n-2)th is f(n-2), and,
f(n) = f(n-1) + f(n-2)
How many ways to finish the first step? 1
How many ways to finish the second step? 2 (1 + 1, or 2)
Thus, we have finished
1. the definition of the state and its transition formula
2. the initialization of the states.
See the code below:
class Solution {
public:
int climbStairs(int n) {
if(n<3) return n;
vector<int> dp(n+1, 0);
dp[1] = 1;
dp[2] = 2;
for(int i=3; i<=n; ++i) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
Comments
Post a Comment