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

Leetcode 70. Climbing Stairs

2016-10-12 21:03 239 查看
题目链接: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?

Subscribe to see which companies asked this question

思路:动态规划,找递推公式,爬到第n级楼梯总的方式:f(n),要么从n-1级爬上来的,要么就是n-2级爬上来的,递推公式:f(n)=f(n-1)+f(n-2)
两种方法,循环和递归,递归超时(功能正确)

代码1:循环

class Solution {
public:
int climbStairs(int n) {
if(n==1||n==2)
return n;
int fn_1=2;
int fn_2=1;
int tmp;
for(int i=3;i<=n;i++)
{
tmp=fn_1+fn_2;
fn_2=fn_1;
fn_1=tmp;
}
return tmp;
}
};


代码2:递归

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