【LeetCode】746. Min Cost Climbing Stairs 使用最小花费爬楼梯(Easy)(JAVA)
题目地址: https://leetcode.com/problems/remove-duplicate-letters/
题目描述:
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].
题目大意
数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 costi。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
解题方法
- 用一个 dp[i] 数组,到达当前位置最小的花费记录下来
- 假设 dp[i] 之前都已经知道,计算 dp[i]: 就是把 dp[i - 1] 和 dp[i - 2] 的最小值加上 cost[i] 即可,因为每次只能爬一个楼梯或者两个楼梯,到当前楼梯只能是爬了一次或者两次
- Note: 因为只用了 dp[i - 1] 和 dp[i - 2] 所以可以只用两个变量表示即可,不需要一个数组
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length];
for (int i = 0; i < cost.length; i++) {
if (i < 2) {
dp[i] = cost[i];
} else {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
}
return Math.min(dp[cost.length - 1], dp[cost.length - 2]);
}
}
执行耗时:1 ms,击败了99.68% 的Java用户
内存消耗:38.3 MB,击败了46.15% 的Java用户