首页 > 代码库 > Leetcode-70 Climbing Stairs

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