746. 使用最小花费爬楼梯 (Swift版本)

题目

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

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

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

限制条件

  • 2 <= cost.length <= 1000
  • 0 <= costi <= 999

Show me the code

swift 复制代码
class Solution {
    var cacheMap = [Int: Int]()
    func minCostClimbingStairs(_ cost: [Int]) -> Int {
        return minCostClimbingStairs(cost, cost.count)
    }

    func minCostClimbingStairs(_ cost: [Int], _ prefixCount: Int) -> Int {
        if let cache = cacheMap[prefixCount] {
            return cache
        }
        if prefixCount == 2 {
            return min(cost[0], cost[1])
        }
        if prefixCount == 3 {
            return min(cost[0] + cost[2], cost[1])
        }
        let ret = min(minCostClimbingStairs(cost, prefixCount - 1) + cost[prefixCount - 1], minCostClimbingStairs(cost, prefixCount - 2) + cost[prefixCount - 2])
        cacheMap[prefixCount] = ret
        return ret
    }
}

执行用时&内存分布

相关推荐
茶底世界之下2 小时前
雨后街口的斑马线:用 Awaking 把颜色让给光与步伐
ios·app·产品
茶底世界之下1 天前
晨雾河岸的旧书摊:用 Awaking 给木色一点暖光
ios·app·产品
90后的晨仔1 天前
在 macOS 27 上运行 Xcode 26
ios
茶底世界之下2 天前
山间站台不必转暖:用 Awaking 留住冷光与红箱
ios·app·产品
songgeb3 天前
YYImage Bug:一行之差,正常 JPEG 如何在 iOS 被读成条纹
ios·swift
fthux3 天前
Tick Rest,一个休息提醒工具的自我修养
macos·开源·swift
茶底世界之下3 天前
阴天花摊不必变暖:用 Awaking 留住花色与湿街
ios·app·产品
Fatbobman(东坡肘子)4 天前
快速消失的硬盘容量 -- 肘子的 Swift 周报 #160
开发语言·人工智能·redis·ios·swiftui·iphone·swift
chaoahyl4 天前
WaterDiary 喝水记录 App 实战(2)· 实现喝水首页与本地保存
swift