题目链接:https://leetcode.com/problems/climbing-stairs/
Runtimes:2ms
1、问题
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?
2、分析
假如有n阶楼梯,可以选择走一步,剩下n-1阶楼梯,可以选择走两步,剩下n-2阶楼梯,接下来就需要继续求n-1,n-2可以有多少种走法,显然是递归事件,递归公式为f(n) = f(n - 1) + f(n - 2),显然是一个斐波拉契序列,用非递归的求法即可完成。
当n = 1, f(1) = 1; 当n = 2, f(2) = 2; 当n = 3, f(3) = 3;当n = 4, f(4) = 5;以此类推。
3、小结
不能用递归解决,太耗费空间,此外容易重复计算已经计算过的数值。
4、实现
class Solution {
public:
int climbStairs(int n) {
int i = 1, presum = 0, sum = 1;
while(i <= n)
{
int temp = sum;
sum += presum;
presum = temp;
++i;
}
return sum;
}
};
5、反思
简单题目,效果不错。