方法一:递归法(超出时间限制)
class Solution {
private:
int recursive(int n){
if(n==0||n==1)
return 1;
return recursive(n-1)+recursive(n-2);
}
public:
int climbStairs(int n) {
return recursive(n);
}
};
方法二:记忆化搜索
class Solution {
private:
vector<int> memo;
int recursive(int n){
if(n==0||n==1)
return 1;
if(memo[n] == -1)
memo[n] = recursive(n-1)+recursive(n-2);
return memo[n];
}
public:
int climbStairs(int n) {
memo = vector<int>(n+1,-1);
return recursive(n);
}
};
方法三:动态规划
class Solution {
public:
int climbStairs(int n) {
vector<int> memo(n+1,-1);
memo[0] = memo[1] = 1;
for(int i=2;i<=n;i++)
memo[i] = memo[i-1]+memo[i-2];
return memo[n];
}
};