Leetcode:70. Climbing Stairs

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];
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/6920625.html