[One question per day] Likou 746. Minimum cost to climb stairs (one-dimensional dynamic programming)

Title description ( portal )

Each index of the array is used as a ladder, and the i-th ladder corresponds to a non-negative physical cost value cost i .

Every time you climb a ladder, you have to spend the corresponding physical cost value, and then you can choose to continue climbing one ladder or climbing two ladders.

You need to find the lowest cost to reach the top of the floor. At the beginning, you can choose the element with index 0 or 1 as the initial ladder.

Example

Example 1:

输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15

Example 2:

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6

Ideas

Read the question first. You may not understand the question the first time, so read it several times.
Each of his states may be reached by the first two states. This problem should be done with dynamic programming.

State definition:
dp[i]: represents the minimum cost to reach the i-th step, so the size here should be cost.length()+1;

Initialization: The
title says that the element with index 0 or 1 can be used as the initial ladder. and so:

dp[0] = 0;// 从 0 开始
dp[1] = 0;// 从 1开始

State equation:
There are two situations in which the i-th layer (i>1) can be reached, that is, one step from the i-1 layer or two steps from the i-2 layer. Choose the smallest among dp[i].

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

Then there is an important question is how to increase his cost? ?
Try it with an example:

cost = [10, 15, 20]

Pay attention to this sentenceThe i-th ladder corresponds to a non-negative physical cost cost[i]
I think it can be understood that cost[i] can be seen as jumping from the i-th step. Whether you jump one or two steps, its cost is cost[i].
Then if dp[i] comes from the i-th step -1 step, then its cost is the cost of the i-1 step, if it comes from the i-2 step, add cost[i-2] directly.
So the state equation is:

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

Return value:
dp[i]

Tip: If it is true, you can try it if you are not sure about the subscript (lazy approach)

Code

 public static  int minCostClimbingStairs(int[] cost) {
    
    
        int len = cost.length;
        int[] dp = new int[len+1];//
        dp[0] = 0;// 从 0 开始
       dp[1] = 0;// 从 1开始
        for (int i = 2; i <= len; i++) {
    
    
            dp[i] = Math.min(dp[i-1]  + cost[i-1]  ,dp[i-2] + cost[i-2] );
        }
        return dp[len];
    }

It may be unclear in some places, welcome to communicate.

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/111468668