跳转至

746. Min Cost Climbing Stairs

Leetcode Array Dynamic Programming

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].
Note: * cost will have a length in the range [2, 1000]. * Every cost[i] will be an integer in the range [0, 999].

分析

这道题目是LeetCode 70. Climbing Stairs的扩展,在Q70中需要求的是爬楼梯有多少种方法,这里求的是爬楼梯最小的费用。思路也是基本一致的:使用动态规划,爬到当前楼梯的最小费用minCost[i]等于爬到前一个楼梯的最小费用minCost[i - 1],和前两个楼梯的最小费用inCost[i - 2]的较小值,加上走到当前楼梯的费用。

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

同样的,也可以省去中间结果:

public int minCostClimbingStairs(int[] cost) {
    int lastCost = 0, secondLastCost = 0, curCost = 0;
    for (int i = 2; i < cost.length + 2; i++) {
        curCost = cost[i - 2] + Math.min(lastCost, secondLastCost);
        secondLastCost = lastCost;
        lastCost = curCost;
    }
    return Math.min(lastCost, secondLastCost);
}