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

Leetcode Climbing Stairs

2015-05-16 19:03 267 查看
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阶或者2阶,问爬上N阶的选择法,爬上1阶的选择1种,爬上2阶的选择有2种,

爬上N阶的选择有f(N) = f(N-1)+f(N-2).....

当使用递归算法的时候会超时!!!!!!

class Solution {
public:
int climbStairs(int n) {
if(n==1)
return 1;
if(n==2)
return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
};


Submission Result: Time Limit Exceeded

改进方法后.......

class Solution {
public:
int climbStairs(int n) {
int result,s1=1,s2=2;
if(n==1)
return s1;
if(n==2)
return s2;
for(int i=3;i<=n;i++)
{
result = s1 + s2;
s1 = s2;
s2 = result;
}
return result;
}
};


Submission Result: Accepted

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: