題目描述
要爬N階樓梯,每次你可以走一階或者兩階,問到N階有多少種走法
測試樣例
Input: 2
Output: 2
Explanation: 到第二階有2種走法
1. 1 步 + 1 步
2. 2 步
Input: 3
Output: 3
Explanation: 到第三階有3種走法
1. 1 步 + 1 步 + 1 步
2. 1 步 + 2 步
3. 2 步 + 1 步
詳細分析
盜用題解一張圖: 在第0階,可以選擇走到第1階或者第2階,第1階可以走第2階或者第3階,第二階可以走第3階或者第4階...。如此繼續就生成了上圖遞歸解答樹。 注意如果直接遞歸會超時,當前實現使用了記憶化儲存子解。
算法實現
記憶化遞歸(√)
class Solution {
public:
int climbStairs(int n) {
this->n = n;
memo = new int[n+2];
for(int i=0;i<n+2;i++){
memo[i] = -1;
}
return recursiveClimbing(0);
}
int recursiveClimbing(int currentStep){
if(memo[currentStep]!=-1){
return memo[currentStep];
}
if(currentStep==n){
return 1;
}
if(currentStep>n){
return 0;
}
memo[currentStep] = recursiveClimbing(currentStep+1) + recursiveClimbing(currentStep+2);
return memo[currentStep];
}
private:
int n;
int total = 0;
int *memo;
};