第7周 Climbing Stairs

Climbing Stairs

Leetcode algorithms problem 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?
    Note: Given n will be a positive integer.

  • 問題提示

  • 思路

    一開始的思路是用排列組合來做,但老是出BUG,大點的數就運算不對,debug到放棄,後面列出前幾種樓梯數情況,發現這可能是個以1和2爲頭的菲波那切數列,嘗試,成功通過

代碼

class Solution {
public:
    int climbStairs(int n) {
        if(n <= 0) return 0;
        if(n == 1) return 1;
        if(n == 2) return 2;
        int sumWays = 0;
        int num1 = 2;
        int num2 = 1;
        for(int i = 2; i < n; i++) {
            sumWays = num1 + num2;
            num2 = num1;
            num1 = sumWays;
        }
        return sumWays;
    }
};

時間複雜度: O(n)
空間複雜度: O(1)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章