[leetcode]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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

分析:

因为每次只能爬1阶或者2阶,所以到达第n阶是从第n-1或者n-2阶爬上来的,所以爬到第n阶的方法总数为到第n-1阶的方法数加上到第n-2阶的方法数。依次递推到n为1和2的的情况,递推公式为:num[n] = num[n-1] + num[n-2]。

class Solution {
public:
    int climbStairs(int n)
 {
//下标从0开始,所以第n阶的方法数为num[n-1]
       if(n == 1)
           return 1;
        vector<int> num(n);
        num[0]=1;
        num[1]=2;
        for(int i=2; i<n; i++)
        {
            num[i] = num[i-1]+num[i-2];
        }
        return num[n-1];
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/83956411
今日推荐