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

70. Climbing Stairs

2016-08-08 22:39 411 查看

1. 问题描述

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?
Tags:Dynamic Programming

2. 解题思路

  简单分析之:

f(1) = 1;

f(2) = 2;

f(3) = f(2) + f(1) = 3

...

f(n) = f(n-1) + f(n-2)

即,Fibonacci数列

3. 代码

class Solution
{
public:
//递归方法:在LeetCode测试,发现超时
int climbStairs_recur(int n)
{
if (1 == n)
{
return  1;
}
else if (2 == n)
{
return 2;
}
else
{
return climbStairs_recur(n-2) + climbStairs_recur(n-1);
}
}
//循环方法:利用了上一次的计算结果,速度快
int climbStairs_loop(int n)
{
if (1 == n)
{
return  1;
}
else if (2 == n)
{
return 2;
}

int cur = 2;
int last = 1;
for (int i=3; i<=n; i++)
{
int t =  last + cur;
last = cur;
cur = t;
}
return cur;
}
};


4. 反思

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