1. 程式人生 > >[LC難題必須要解決系列][之][DP] Min Cost Climbing Stairs

[LC難題必須要解決系列][之][DP] Min Cost Climbing Stairs

問題 ssi span 序列 Once pan house tput cos

Min Cost Climbing Stairs

https://leetcode.com/problems/min-cost-climbing-stairs/

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Intuition:

這題要求最小cost,也是求極值問題,可以想到用DP。同時我們也可以清楚知道這和paint house一樣也屬於狀態序列類問題,假設我們用一維數組f[i] 表示前i個樓梯要花的最小cost,這樣我們的最後一步就是前n個樓梯要花的最小cost。

方程:f[i] = Math.min(f[i-1], f[i-2]) + A[i];

初始:f[0] = A[0], f[1] = A[0] + A[1];

計算順序:從0到n,結果取f[n-1];

Time conplexity: O(n);

    public int minCostClimbingStairs(int[] A) {
        int n = A.length;
        int[] f = new int[n];
        f[0] = A[0];
        f[1] = A[1];
        
        for (int i = 2; i < n; i ++){
            f[i] 
= Math.min(f[i-1], f[i-2]) + A[i]; } return Math.min(f[n-2], f[n-1]); }

Climbing Stairs

https://leetcode.com/problems/climbing-stairs/

這個題也是一樣能求極值問題想到DP,從最後一步考慮我們可以快速得到方程,f[i-1] + f[i-2]。這裏就不詳細寫思路了。

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

[LC難題必須要解決系列][之][DP] Min Cost Climbing Stairs