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.

Subscribe to see which companies asked this question.

解析:

這個問題似乎是一個動態規劃問題。提示:標籤也表明!
下面是逐步獲得解決方案的步驟。
基本情況:
如果n=0,則路徑數應爲零。
如果n=1,那麼只有爬樓梯的方法。
如果n=2,那麼有兩種爬樓梯的方法。一個解決辦法是一個接一個,另一個是一次兩步。
解決問題的關鍵的直覺是,給定數量的樓梯,如果我們知道去點[ 1 ]和[ 2 ]分別數的方法,記爲N1和N2,然後去點[ ]是N1 + N2總的方法。因爲從n-1點,我們可以採取一個步驟達到[ n ]。從[ 2 ],我們可以採取兩個步驟有。這兩個解決方案集之間沒有重疊,因爲我們在最後一步中有不同之處。
現在,根據上面的直覺,我們可以構造一個數組,在這個數組中每個節點都存儲每個n的解,或者如果我們更仔細地看它,很明顯這基本上是一個斐波那契數,起始數爲1和2,而不是1和1。


程序:

class Solution {
public:
    int climbStairs(int n) {
    // base cases
    if(n <= 0) return 0;
    if(n == 1) return 1;
    if(n == 2) return 2;
    
    int one_step_before = 2;
    int two_steps_before = 1;
    int all_ways = 0;
    
    for(int i=2; i<n; i++){
    all_ways = one_step_before + two_steps_before;
    two_steps_before = one_step_before;
        one_step_before = all_ways;
    }
    return all_ways;
}
};

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