leetcode70.爬樓梯

  1. 題目:
    假設你正在爬樓梯。需要 n 階你才能到達樓頂。
    每次你可以爬 1 或 2 個臺階。你有多少種不同的方法可以爬到樓頂呢?
    注意:給定 n 是一個正整數。
  2. 示例:
    示例 1:
    輸入: 2
    輸出: 2
    解釋: 有兩種方法可以爬到樓頂。
    1 階 + 1 階
    2 階
    示例 2:
    輸入: 3
    輸出: 3
    解釋: 有三種方法可以爬到樓頂。
    1 階 + 1 階 + 1 階
    1 階 + 2 階
    2 階 + 1 階
  3. 思路:
    遞歸思路:
    在這裏插入圖片描述
  4. 代碼:
    遞歸實現:
class Solution {
public:
    int climbStairs(int n) {
        return calcWays(n);
    }
private:
    int calcWays(int n){
        if(n==1) return 1;
        if(n==2) return 2;
        return calcWays(n-1)+calcWays(n-2);
    }
};

動態規劃:

    int climbStairs(int n) {
        vector<int> res(n+1,-1);
        res[0]=1;
        res[1]=1;
        for(int i=2;i<=n;i++)
            res[i]=res[i-1]+res[i-2];
        return res[n];
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章