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

LeetCode 70:Climbing Stairs

2015-12-14 12:02 417 查看
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项和,关键是一开始我用递归时居然提示我超时。。。没办法只好用了迭代(虽然我觉得递归更好理解)

/*class Solution {
public:
int climbStairs(int n) {
if(n==1) return 1;
else if (n==2) return 2;
else return climbStairs(n-1)+climbStairs(n-2);
}
};
*/
class Solution {
public:
int climbStairs(int n) {
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 2;
else
{
int x=0,y=1,z=0,sum=2;
for(int i=3;i<=n;i++)
{
z=x+y;
x=y;
y=z;
sum+=y;
}
return sum;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: