Leetcode-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

Explain

這道題是關(guān)于動態(tài)規(guī)劃的。很經(jīng)典。這道題如果用遞歸做,會出現(xiàn)太慢的情況。雖然遞歸的思想我個(gè)人覺得是很正確的。那沒辦法,只能用動態(tài)規(guī)劃做。每次只能走一階或兩階。那么我們想想,如果要到第三階,這個(gè)時(shí)候就相當(dāng)于已經(jīng)走了一階,現(xiàn)在選擇兩階和已經(jīng)走了兩階,現(xiàn)在選擇走一階。那么 DP[n] = DP[n-1] + DP[n-2] 動態(tài)規(guī)劃的狀態(tài)方程是不是就出來了。那么下面上代碼

Code

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

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

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