0%

746-使用最小花费爬楼梯

题目地址:https://leetcode.cn/problems/min-cost-climbing-stairs

题目

给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。

你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。

请你计算并返回达到楼梯顶部的最低花费

理解

此题需要动态规划来解决。首先,new一个数组,长度需要比给定的接替数组多一位。 题中说可以从0或1开始,那么dp的第一位和第二位就都可以是0。

然后从cost的第二位开始循环,比较已经累计的dp[i-1]和cost[i-1]的和与dp[i-2]和cost[i-2]的和的大小,取较小值赋值给dp[i]。

最后返回dp[n]即可。

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number[]} cost
* @return {number}
*/
var minCostClimbingStairs = function(cost) {
const n = cost.length
const dp = new Array(n + 1)
dp[0] = dp[1] = 0
for(let i = 2; i <= n; i ++) {
dp[i] = Math.min(dp[i-1] + cost[i - 1], dp[i - 2] + cost[i - 2])
}
return dp[n]
};