Leetcode-70 Climbing Stairs

Posted 北冥有鱼,南冥有猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode-70 Climbing Stairs相关的知识,希望对你有一定的参考价值。

#70.    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?

题解:这道题属于动态规划的题,类似于斐波那契数列,所以采用非递归的方式来解。当楼梯只有一级时,显然只有一种方法,即f(1)=1;当楼梯有两级时,显然有两种方法,即f(2)=2;当楼梯有n级时,f(n) = f(n-1) + f(n-2);

class Solution {
public:
    int climbStairs(int n) {
        if(n<=2)
        {
            return n;
        }
        int array[n+1]={0};
        array[1]=1;
        array[2]=2;
        for(int i=3;i<=n;i++)
        {
            array[i]=array[i-1]+array[i-2];
        }
        return array[n];
    }
};

 

以上是关于Leetcode-70 Climbing Stairs的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 70. Climbing Stairs

Leetcode-70 Climbing Stairs

Leetcode 70 Climbing Stairs

[Leetcode 70]: Climbing Stairs

[leetcode]70.Climbing Stairs

LeetCode 70. Climbing Stairs