LeetCode 746. 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].

这道题还是一维动态规划题,分析略过。

只是注意到,递归关系从第4项开始才成立。

代码如下:

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        if(cost==null || cost.length==0) return 0;
        if(cost.length==1) return cost[0];
        if(cost.length==2) return Math.min(cost[0],cost[1]);
        if(cost.length==3) return Math.min(cost[1],cost[0]+cost[2]);
        
        int[] f = new int[cost.length];//f[i]: 最后落脚处小于等于i时的minimum cost
        f[0] = cost[0];
        f[1] = Math.min(cost[0],cost[1]);
        f[2] = Math.min(cost[1],cost[0]+cost[2]);//f[2]不满足递推关系
        for(int i = 3;i<f.length;i++){
            f[i] = Math.min(f[i-1] + cost[i], f[i-2]+cost[i-1]);
        }
        return f[f.length-1];
    }
}

--------------------------------------------------------------------------------------------------------------------

更新:

今天复习了一下这个题,看到最高赞答案,代码好简单。。。

对于每个台阶,都记录最后落脚在该台阶并从该台阶跳出去(一步或两步)的最小可能cost

     第一级和第二级,这个值分别就是第一级和第二级台阶自己的cost

    从第三级台阶开始,对每一级台阶,这个最小可能cost由两项构成:

            (1)到达该台阶的最小cost。想要到达该级台阶只有两种可能:最后落脚处为前一级台阶或者前前一级(前两级)台阶

                      因此这一项为   min(cost[i-1], cost[i-2])

            (2)该级台阶自己的cost

              故而为cost[i] = cost[i] + min(cost[i-1,cost[i-2])

     那么最后,要么从最后一级落脚并跳出,要么从倒数第二级台阶落脚并跳出,取最小值即可。

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

猜你喜欢

转载自blog.csdn.net/qq_39638957/article/details/88686403