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

Leetcode: 70. Climbing Stairs

2016-05-01 12:05 645 查看
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比较大的话内存爆了那是妥妥的。

就按照
f(n) = f(n-1) + f(n-2)
来计算。

递归

int fibolaci(int a,int b,int i,int n)
{
if(i>n)
{
return b;
}
return fibolaci(b,a+b,i+1,n);
}
int climbStairs(int n) {
return fibolaci(0,1,1,n);
}


o(n) + o(1)

int climbStairs(int n) {
int pre = 1;
int cur = 1;
int step = 1;
int temp ;
while(step<n)
{
temp = cur;
cur = cur + pre;
pre = temp;
step++;
}
return cur;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: