Description

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.

思路

  • 动态规划,dp[i] 表示爬到第i阶共有多少种方法,dp[1] = 1, dp[2] = 2
  • dp[i] = dp[i - 1] + dp[i - 2]

代码

class Solution {
public:
    int climbStairs(int n) {
        vector<int> vec(n, 0);
        vec[0] = 1;
        vec[1] = 2;
        for(int i = 2; i < n; ++i)
            vec[i] = vec[i - 1] + vec[i - 2];
        
        return vec[n - 1];
    }
};

相关文章:

  • 2021-07-13
  • 2021-10-29
  • 2021-10-21
  • 2021-12-08
  • 2021-10-08
  • 2022-12-23
猜你喜欢
  • 2021-07-23
  • 2021-08-06
  • 2022-01-04
  • 2022-01-27
  • 2021-09-29
  • 2021-10-05
相关资源
相似解决方案