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.

Example 1:

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

  1. 1 step + 1 step
  2. 2 steps

解法:
這個(gè)也是斐波那契數(shù)列的一個(gè)變種,好多題目都喜歡考這個(gè),本質(zhì)上是一樣的??紤]到最后一步可以跨一步或者兩步,那么s(n) = s(n-1) + s(n-1)

class Solution {
public:
    int climbStairs(int n) {
        if(n == 1) {
            return 1;
        }
        
        if(n == 2) {
            return 2;
        }
        
        int curResult = 2;
        int lastResult = 1;
        for(int i=3; i<=n; i++) {
            int temp = curResult;
            curResult = curResult + lastResult;
            lastResult = temp;
        }
        return curResult;
    }
};

依然需要注意一下邊界,最好可以在腦海里面代入具體的值演算一遍。不要犯低級(jí)錯(cuò)誤。

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

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

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