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?
思路。
f(n)表示爬到n层楼梯的方法。f(n) = f(n-1)+f(n-2)。因此,可以用递归和迭代处理,递归中很多的重复计算,效率太慢。使用迭代,时间复杂度O(n),空间复杂度O(1)。
class Solution{
public:
static int climb(int n)
{
int pre = 0;
int cur = 1;
for(int i = 1;i <=n;++i)
{
int tmp = cur;
cur+=pre;
pre=tmp;
}
return cur;
}
};