题目:
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?
题解:可以由递推关系得出,例如,当台阶为1阶时,S1=1,台阶为2时,第一步你可以选择两种情况,1)只踏一步,所以剩余的为S1, 2)踏两步,剩余的为0。台阶为3时,第一步选择也有两种情况,1)只踏一步,剩余的为S2,2)只踏两步,剩余的为S1.。。。所以,当为n个台阶时,1)第一步只踏一步,剩余为S(n-1),2)第一步踏两步,剩余未S(n-2)。所以,S(n) = S(n-1) + S(n-2)。属于分治问题
最后要注意的是,如果用递归,则需重复计算许多子问题,可以动态规划解决。代码如下
class Solution {
public:
int climbStairs(int n) {
int *array = new int[n];
memset(array, 0, n*sizeof(int));
array[0]=1;
array[1]=2;
for (int i=2; i<n; i++)
{
array[i]=array[i-1]+array[i-2];
}
return array[n-1];
}
};