[leetcode - Bliend-150 ] 746. Min Cost Climbing Stairs (Easy

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 twosteps.

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)
http://img2.58codes.com/2024/20124767RBMCuj4LV9.jpg
costs = [10,15,30] 要走到 30 则有两种方式
http://img2.58codes.com/2024/20124767C7rGKIOM9s.jpg从 10 走两步,从起点走到 10 花费的最少金额在 1 已经算过并放在 dp[0] 中将他和 30 相加
http://img2.58codes.com/2024/20124767686A2spoPj.jpg从 15 走一步,从起点走到 15 花费的最少金额在 2 已经算过并放在 dp[1] 中将他和 30 相加
http://img2.58codes.com/2024/201247674o313ZyAYA.jpg两种走法取最小的放入 dp 中代表从起点走到 30 所花费的最少金额
http://img2.58codes.com/2024/20124767jxStgZ5l1N.jpg
costs = [10,15,30,5] 要走到 5 则有两种方式从 15 走两步,从起点走到 15 花费的最少金额在 2 已经算过并放在 dp[1] 中将他和 5 相加
http://img2.58codes.com/2024/201247676qw8PiFv4V.jpg从 30 走一步,从起点走到 30 花费的最少金额在 3 已经算过并放在 dp[2] 中将他和 5 相加
http://img2.58codes.com/2024/20124767vblU4mwp3C.jpg两种走法取最小的放入 dp 中代表从起点走到 5 所花费的最少金额
http://img2.58codes.com/2024/20124767Fk75BYVaF9.jpg
costs = [10,15,30,5,20] 要走到 20 则有两种方式从 30 走两步,从起点走到 30 花费的最少金额在 3 已经算过并放在 dp[2] 中将他和 20 相加
http://img2.58codes.com/2024/20124767S3v5p6Z49Z.jpg从 5 走一步,从起点走到 5 花费的最少金额在 4 已经算过并放在 dp[3] 中将他和 20 相加
http://img2.58codes.com/2024/201247678AFGAxxcUo.jpg两种走法取最小的放入 dp 中代表从起点走到 20 所花费的最少金额
http://img2.58codes.com/2024/20124767oIK97OHOV7.jpg
已经计算完走到楼梯最后一阶为止所要花费的金额,要完全走完楼梯就有两种方法从 5 走两步离开楼梯
http://img2.58codes.com/2024/20124767YFWlLDfRIW.jpg从 20 走一步离开楼梯
http://img2.58codes.com/2024/201247674X9kS1uldj.jpgdp[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]);};

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章