70. 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.

一刷
題解:dynamic programming,且存在遞歸的表達(dá)式a[n] = a[n-1] + a[n-2]

方法一:直接用遞歸,但會(huì)造成超時(shí),可能是數(shù)字太大時(shí)棧太長(zhǎng)。并且比起用數(shù)組存起來(lái)中間結(jié)果不會(huì)更節(jié)約space。

public class Solution {
    public int climbStairs(int n) {
        if(n == 1 || n==0) return 1;
        if(n<0) return 0;
        return climbStairs(n-1) + climbStairs(n-2);
    }
}

方法二:用數(shù)組存起來(lái)中間結(jié)果。

public class Solution {
    public int climbStairs(int n) {
        int[] res = new int[n+1];
        res[0] = 1;
        res[1] = 1;
        for(int i=2; i<=n; i++){
            res[i] = res[i-1] + res[i-2];
        }
        return res[n];
    }
}

方法三,用常量存儲(chǔ) res[i-1], res[i-2]; 將space complexity降到O(1)

public class Solution {
    public int climbStairs(int n) {
        if(n == 1 || n==0) return 1;
        if(n<0) return 0;
        int oneStep = 1, twoStep = 2;
        if(n == 1) return oneStep;
        if(n == 2) return twoStep;
        int sum = 0;
        for(int i=3; i<=n; i++){
            sum = oneStep + twoStep;
            oneStep = twoStep;
            twoStep = sum;
        }
        return sum;
    }
}
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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