You are given an integer array cost where cost[i]
is the cost of ith step on a staircase. Once you pay the cost, you can either climb one
or two
steps.
You can either start from the step with index 0
, or the step with index 1
.
Return the minimum cost to reach the top of the floor.
给一个 array cost 纪录每一步的花费,每次可以前进一步或两部,只能从 cost 的 index = 0 或 index = 1 开始,找出花费最少的值。
Step
costs = [10],则只有一种方法costs = [10,15] 则有两种方法,从 index = 0 出发 (10+15) 或从 index = 1 出发 (15)
costs = [10,15,30] 要走到 30 则有两种方式

1
已经算过并放在 dp[0]
中将他和 30 相加
2
已经算过并放在 dp[1]
中将他和 30 相加
30
所花费的最少金额
costs = [10,15,30,5] 要走到 5 则有两种方式从 15 走两步,从起点走到 15 花费的最少金额在
2
已经算过并放在 dp[1]
中将他和 5 相加
3
已经算过并放在 dp[2]
中将他和 5 相加
5
所花费的最少金额
costs = [10,15,30,5,20] 要走到 20 则有两种方式从 30 走两步,从起点走到 30 花费的最少金额在
3
已经算过并放在 dp[2]
中将他和 20 相加
4
已经算过并放在 dp[3]
中将他和 20 相加
20
所花费的最少金额
已经计算完走到楼梯最后一阶为止所要花费的金额,要完全走完楼梯就有两种方法从 5 走两步离开楼梯


dp[3]
, dp[4]
分别纪录了走到 5 和走到 20 所花费的最少金额,所以可以看出从 5 走两步离开楼梯金额是最少的。Coding
var minCostClimbingStairs = function(cost) { const dp = [cost[0], cost[1]]; for(let i = 2; i < cost.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]);};