You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
解析:
本題是個動態規劃問題,最優解可有子問題的的最優解組成,具有重復的子問題。
由題目可知要求到達第n階台階的所有方法f(n),又每次能登1~2個台階,
- 從 n-1 階登 1 步 到達 n 階
- 從 n-2 階登 2 步 到達 n 階
因此
難點在於想到遞歸式,對於遞歸問題注意從後往前看。
class Solution {
public:
// f(n) = f(n-1)+f(n-2)
int climbStairs(int n) {
int prev = 0;
int cur = 1;
for(int i = 1; i <= n; i++) {
int temp = cur;
cur += prev;
prev = temp;
}
return cur;
}
};