Dynamic programming problem solution and analysis

Dynamic programming problem solution and analysis

Question 1:

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 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: The minimum cost is to start from cost[1], and then take two steps to reach the top of the ladder, a total cost of 15.
Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: The lowest cost method is to start from cost[0], go through the 1s one by one, skip cost[ 3], it costs a total of 6.

Solution 1:

Method: Dynamic programming The
calculation cost f[i] has a clear recursive relationship: f[i] = cost[i] + min(f[i+1], f[i+2]). We can use dynamic programming to achieve this.

algorithm:

When we want to calculate f[i], we must first calculate f[i+1] and f[i+2]. So we should calculate f from back to front.
In step i, let f1, f2 be the old values ​​of f[i+1], f[i+2], and update them to the new values ​​of f[i], f[i+1]. When we traverse i from the back, we will keep these updates. At the end the answer is min(f1, f2).

code show as below

public int minCostClimbingStairs(int[] cost) {
    
    
        int f1=0, f2=0;
        for (int i = cost.length-1; i >= 0 ; i--) {
    
    
            int f0=cost[i]+Math.min(f1,f2);
            f2=f1;
            f1=f0;
        }
        return Math.min(f1,f2);
    }

Guess you like

Origin blog.csdn.net/weixin_43372169/article/details/109852169