[LeetCode] 746. 使用最小花费爬楼梯 ☆(动态规划)

描述

数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。

每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

示例 1:

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

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

cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。

解析

一次只能爬1个阶梯或者2个阶梯。那么位置 i 的最小值花费 f(i) = Math.min(f(i - 1), f(n - 2)) + cost[i]。

要达到题目要求,那么就是比较 f(cost.length - 1) f(cost.length - 2)中较小值即可,因为这2个位置可以直接一步满足题目要求。

代码

一维数组

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

一维数组优化

public static int minCostClimbingStairs(int[] cost) {
        int first = cost[0];
        int second = cost[1];
        for (int i = 2; i < cost.length; i++) {
            int curMin = Math.min(first, second) + cost[i];
            first = second;
            second = curMin;
        }
        return Math.min(first, second);
    }
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/12188093.html