Dynamic Programming Leetcode of topics (DP) -746. The minimum cost of using the stairs (Min Cost Climbing Stairs)

Dynamic Programming Leetcode of topics (DP) -746. The minimum cost of using the stairs (Min Cost Climbing Stairs)


 Each index of the array as a ladder, the first  ione corresponding to the physical step takes a non-negative value  cost[i](the index starts from 0).

Every time you climb a ladder you have to take physical cost value corresponding to, and then you can choose to continue to climb a ladder or climbing two steps.

You need to find the lowest cost at the top floor. In the beginning, you can choose from index 0 or 1 as the initial elements of the ladder.

Example 1:

Input: cost = [10, 15, 20] 
Output: 15 
Explanation: minimum cost from cost [1] Start, then take a step to the top in two steps, spent a total of 15.

 Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 
Output: 6 
Explanation: from the lowest cost approach is cost [0] starts, one by one after that, skips cost [ 3], spent a total of 6.

note:

  1. cost The length will be  [2, 1000].
  2. Each  cost[i] will be an Integer type range  [0, 999].

 

DP:

DP [i] denotes the i-th minimum cost to the stairs.

Pay attention to several points:

1, the roof is the subscript cost.length

2, where you start index is -1 or -2 (since one can take once, if you are in one single pass -1 if the time you go layer 2 -2)

In order to optimize these points, we have an array of length dp + 3.

State transition equation:

dp[i] = Math.min(dp[i-1],dp[i-2])+cost[i-2];

 

 

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] dp = new int[cost.length + 3];
        dp[0] = 0;
        dp[1] = 0;
        for (int i = 2; i < dp.length; i++) {
            if(i==dp.length-1){
                dp[i] = Math.min(dp[i-1],dp[i-2]);
            }else{
                dp[i] = Math.min(dp[i-1],dp[i-2])+cost[i-2];
            }
        }
        return dp[dp.length-1];
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11482076.html