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?
意思就是爬一个n个台阶的楼梯,每次只能爬1个或2个台阶,问有多少种方法。
思路:爬n个台阶可有两种大的方案:爬 n-2 个台阶后再一次爬 2 个台阶;或者爬 n-1 个台阶后再爬 1 个台阶。所以得出规律:设方案个数为 S[n],则 S[n]=S[n-1]+S[n-2],S[1]=1,S[2]=2 , 这是一个斐波那契数列。
class Solution {
public:
int climbStairs(int n) {
if (n <= 2)
return n;
int a = 1, b = 2, ans = 0;
for (int i = 2; i<n; ++i){
ans = a + b;
a = b;
b = ans;
}
return ans;
}
};
也可以用一个数组存储所有结果,更简单,但是消耗了一个大小为 n 个 int 空间,不是好的解法。上面解法仅消耗三个 int 的空间。
class Solution {
public:
int climbStairs(int n) {
int* num=new int[n];
num[0]=1;
num[1]=2;
for(int i=2;i<n;++i)
num[i]=num[i-1]+num[i-2];
return num[n-1];
}
};