使用最小花费爬楼梯
题目:使用最小花费爬楼梯
给你一个整数数组cost,其中cost[i]是从楼梯第i个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为0或下标为1的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
遇到这种问题首先想到的就是使用递归,我们先把复杂问题简单化,
- cost长度为1时,最小花费为0
- cost长度为2时,最小花费为Math.min(cost[0], cost[1])
- cost长度为3时,最小花费为Math.min(cost[0] + cost[2], cost[1])
- cost长度为4时,最小花费为Math.min(cost.slice(0, cost.length - 1)的最小值+cost[cost.length - 1], cost.slice(0, cost.length - 2)的最小值+cost[cost.length - 2])
通过观察上面的规律我们可以得出如下结论:最小花费可以简化成有没有包含最后一个台阶
cost.length - 1,最后去两者的最小值,如下: 包含最后台阶:cost[cost.length - 1]加上cost.length - 2及以前台阶的最小值。 不包含最后台阶:cost[cost.length - 2])加上cost.length - 3,不包含最后台阶说明最后一步为length-2则剩余台阶为0到length-3
var minCostClimbingStairs = function(cost) {
if (cost.length == 1 || cost.length == 0) return 0
if (cost.length == 2) return Math.min(cost[0], cost[1])
// 包含最后台阶
let last = minCostClimbingStairs(cost.slice(0, cost.length - 1)) + cost[cost.length - 1]
// 不包含最后台阶
let noLast = minCostClimbingStairs(cost.slice(0, cost.length - 2)) + cost[cost.length - 2]
return Math.min(last, noLast)
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
使用上面的递归方式十分浪费性能,这里同样使用动态规划来优化
let arr = new Array(cost.length+1)
arr[0] = 0,arr[1]=0
for(let i = 2; i <= cost.length; i++) {
arr[i] = Math.min(arr[i - 1] + cost[i - 1], arr[i - 2] + cost[i - 2])
}
return arr[cost.length]
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2025/09/05, 8:09:00