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

LeetCode(70)题解: climbing-stairs

2015-08-08 15:07 288 查看
https://leetcode.com/problems/climbing-stairs/

题目:

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)递归: 超时

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


2)非递归, 避免嵌套调用

递推公式

a_n=a_{n-1}+a_{n-2}.

a_1=1, a_2=2.

问题:给定n求a_n。其实就是斐波那契数列。

AC代码:

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