您的位置:首页 > 大数据 > 人工智能

[LeetCode] Climbing Stairs

2014-07-25 23:36 239 查看
题目:

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
;
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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode 算法