1. 程式人生 > >[leetcode] 70. 爬樓梯

[leetcode] 70. 爬樓梯

ble i++ 條件 == ++ 爬樓梯 樓梯 for script

70. 爬樓梯

最簡單的動態規劃

假設f[i]表示爬到第i層有幾種爬法

那麽狀態轉移方程為:f[i] = f[i-1] + f[i-2]

初始條件顯然是:f[1]=1,f[2] = 2;

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

[leetcode] 70. 爬樓梯