class Solution {
public:
int climbStairs(int n) {
if(n == 0)
return 0;
if(n == 1)
return 1;
if(n == 2)
return 2;
return climbStairs(n - 1) + climbStairs(n - 2);
}
};
这道题相当于unique paths的一维简化版本。第一眼能想到的思路就是递归的方式,
但是同在计算斐波那契额数列中使用递归一样,违反了合成效率法则,其中的有些项
进行了多次重复计算,使得时间复杂度大大提高,因此,可以用动态规划的思路将其改写
为迭代的形式
class Solution {
public:
int climbStairs(int n) {
int way[n];
way[0] = 1;
way[1] = 2;
for(int i = 2; i < n; i++)
{
way[i] = way[i-1] + way[i-2];
}
return way[n - 1];
}
};
其中台阶高度i的走法way[i]依赖于way[i -1] 和way[i -2]的值,
而基准情况是way[o]和way[1]也就是台阶高度分别为1,和2的情况。
另外一种不用额外空间的方法
class Solution {
public:
int climbStairs(int n) {
if(n == 1)
return 1;
if(n == 2)
return 2;
int nextToLast = 1;
int last = 2;
int answer;
for(int i = 3; i <= n; i++)
{
answer = nextToLast + last;
nextToLast = last;
last = answer;
}
return answer;
}
};