leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

746. 使用最小花费爬楼梯

Open buuing opened this issue 3 years ago • 1 comments

数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。

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

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 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。

注意:

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

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




为了方便理解, 我一开始就 push 一个空台阶进去. 这样做的好处是为了不再考虑最后一节台阶到底是跳还是不跳, 然后我只需要专心的判断前面的状态该如何存储

  • 记忆化递归
const minCostClimbingStairs = cost => {
  cost.push(0)
  const memo = []
  const dfs = (index) => {
    if (index < 0) return 0
    if (!memo[index]) {
      memo[index] = Math.min(
        dfs(index - 1) + ~~cost[index - 1],
        dfs(index - 2) + ~~cost[index - 2]
      )
    }
    return memo[index]
  }
  dfs(cost.length - 1)
  return memo[cost.length - 1]
}
  • 动态规划
const minCostClimbingStairs = cost => {
  cost.push(0)
  const dp = []
  for (let i = 0; i < cost.length; i++) {
    dp[i] = Math.min(
      ~~dp[i - 1] + ~~cost[i - 1],
      ~~dp[i - 2] + ~~cost[i - 2]
    )
  }
  return dp[cost.length - 1]
}

buuing avatar Dec 22 '20 12:12 buuing