Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

使用最小花费爬楼梯-746 #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sl1673495 opened this issue May 5, 2020 · 0 comments
Open

使用最小花费爬楼梯-746 #13

sl1673495 opened this issue May 5, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

sl1673495 commented May 5, 2020

数组的每个索引做为一个阶梯,第  i 个阶梯对应着一个非负数的体力花费值  costi

每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

示例  1:

输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从 cost[1]开始,然后走两步即可到阶梯顶,一共花费 15。
  示例 2:

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从 cost[0]开始,逐个经过那些 1,跳过 cost[3],一共花费 6。
注意:

cost  的长度将会在  [2, 1000]。
每一个  cost[i] 将会是一个 Integer 类型,范围为  [0, 999]。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

经典的 DP 问题,先从最后的台阶开始求最小花费值,每一层可以选择走一步或走两步,

状态转移方程是:dp[i] = Math.min(oneStep, twoStep)。

题解

/**
 * @param {number[]} cost
 * @return {number}
 */
let minCostClimbingStairs = function (cost) {
  let dp = [];

  for (let i = cost.length - 1; i >= 0; i--) {
    let oneStep = cost[i] + (dp[i + 1] || 0);
    let twoStep = cost[i] + (dp[i + 2] || 0);

    dp[i] = Math.min(oneStep, twoStep);
  }

  return Math.min(dp[0], dp[1]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant