leetcode 70. Climbing Stairs DP动态规划 + 斐波那契序列

来源:互联网 发布:搜狐快站绑定独立域名 编辑:程序博客网 时间:2024/05/21 08:39

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?

Note: Given n will be a positive integer.

这道题就是经典的爬楼梯问题,其实就是斐波那契数列,不说了直接上代码。

代码如下:

public class Solution{    public int climbStairs(int n)     {        if(n>=3)        {            int []step=new int[n+1];            step[0]=0;            step[1]=1;            step[2]=2;            for(int i=3;i<n+1;i++)                step[i]=step[i-1]+step[i-2];            return step[n];        }else            return n;       }    /*     * 这个是递归解法,会发现递归会超时     * */    public int byRecursion(int n)    {        if(n<=0) //小于0层的时候没有解决方法            return 0;        else if(n<=1) //只有一层的时候只有一种解决办法(走1层)            return 1;        else if(n<=2) //有两层的时候有两种解决办法(走1层或者2层)            return 2;        else  //下面是递归调用            return byRecursion(n-1) + byRecursion(n-2);    }}

下面是C++的答案,就是一个斐波那契序列

代码如下:

#include <iostream>#include <cmath>using namespace std;class Solution{public:    int climbStairs(int n)    {        if (n >= 3)        {            int* step = new int[n+1];            step[0] = 0;            step[1] = 1;            step[2] = 2;            for (int i = 3; i <= n; i++)                step[i] = step[i - 1] + step[i - 2];            return step[n];        }        else            return n;    }};
阅读全文
0 0