Leetcode 70. Climbing Stairs

来源:互联网 发布:广东省网络作家协会 编辑:程序博客网 时间:2024/05/20 20:58

题目链接: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;    }};


0 0
原创粉丝点击