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?
其实想想就是一个斐波拉契数列,考虑:
s(n) = s(n-1) + s(n-2);
s(1) = 1;
s(2) = 2;
s(3) = s(1) + s(2) = 3;
class Solution {
public:
int climbStairs(int n) {
if (n == 1)
return 1;
else if (n == 2)
return 2;
else
{
int first = 1;
int second = 2;
for (int i=2; i<n; i++)
{
int temp = second;
second = first + second;
first = temp;
}
return second;
}
}
};
145

被折叠的 条评论
为什么被折叠?



