爬樓梯 -簡(jiǎn)單動(dòng)態(tài)規(guī)劃

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.
每次爬1到2步有多少種方法可以爬上n階臺(tái)階
思路:
n=1時(shí) 有1種方法
n=2時(shí),有兩種方法
n=3時(shí),有先爬到臺(tái)階2再爬1步(此處有f(2)種方法,最后一步唯一且確定),與先爬到臺(tái)階1再爬2步(此處有f(1)種方法,最后一步唯一且確定)兩種策略,共f(2)+f(1)
n=4時(shí),有先爬到臺(tái)階3再爬1步,與先爬到臺(tái)階2再爬2步兩種策略,共f(3)+f(2)
n=5時(shí),.....
即有f(n)=f(n-1)+f(n-2)

var climbStairs = function(n) {
    var res = []
    res[1] = 1
    res[2] = 2 
    for(var i =3; i<n; i++){
        res[i] = res [i-1] + res [i-2]
    }
    return res[n]
};
最后編輯于
?著作權(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)容