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.

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

My code:

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    let num1 = 1, num2 = 2, temp = 0;
    if(n == 1 || n == 2) {
        return n;
    }
    for(let i = 3; i <= n; i++) {
        temp = num1 + num2;
        num1 = num2;
        num2 = temp;
    }
    return temp;
};

Note: 簡單算一下前幾個結(jié)果可以看出是斐波那契數(shù)列

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,014評論 0 23
  • 在微博上面發(fā)現(xiàn)有人曬這個炸玉米,而且看上去很好吃的樣子,就想自己試一下能不能做出來。 最后發(fā)現(xiàn)其實做法就和做洋蔥圈...
    勁紋兒的廚房閱讀 2,391評論 22 69
  • 不是說要虛偽到阿諛奉承,只是人總要懂得些人情世故,哪怕你不去特意做,你也要懂。和別人交流過程中,我們總要學(xué)著怎么讓...
    遇見活在當(dāng)下的自己閱讀 189評論 0 0

友情鏈接更多精彩內(nèi)容