746. 使用最小花费爬楼梯
给你一个整数数组 cost
,其中 cost[i]
是从楼梯第 i
个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0
或下标为 1
的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
示例 1:
输入:cost = [10,15,20]
输出:15
解释:你将从下标为 1 的台阶开始。
- 支付 15 ,向上爬两个台阶,到达楼梯顶部。
总花费为 15 。
示例 2:
输入:cost = [1,100,1,1,1,100,1,1,100,1]
输出:6
解释:你将从下标为 0 的台阶开始。
- 支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。
- 支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。
- 支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。
- 支付 1 ,向上爬一个台阶,到达楼梯顶部。
总花费为 6 。
提示:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
解法
1. 递归
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public int minCostClimbingStairs(int[] cost) {
return climb(cost, 0, -1);
}
public int climb(int[] cost, int curCost, int pos) {
if (pos >= cost.length) {
return curCost;
}
int posCost = pos == -1 ? 0 : cost[pos];
if (map.containsKey(pos) && map.get(pos) < (curCost + posCost)) {
return map.get(pos);
}
int cost1 = climb(cost, curCost + posCost, pos + 1);
int cost2 = climb(cost, curCost + posCost, pos + 2);
curCost = Math.min(cost1, cost2);
map.put(pos, curCost);
return curCost;
}
}
虽然递归可以求解,但是在LeetCode上会超时。
2. 迭代
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < dp.length; i++) {
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);
}
return Math.min(dp[dp.length - 1], dp[dp.length - 2]);
}
}