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

题目

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

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

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

限制条件

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 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
    }
}

执行用时&内存分布

相关推荐
WDeLiang3 小时前
Flutter 环境搭建
flutter·ios·visual studio code
lilili啊啊啊11 小时前
iOS 应用性能测试工具对比:Xcode Instruments、克魔助手与性能狗
测试工具·ios·iphone·xcode·克魔
264玫瑰资源库1 天前
嘻游电玩三端客户端部署实战:PC + Android + iOS 环境全覆盖教程
android·ios
鸿蒙布道师1 天前
鸿蒙NEXT开发权限工具类(申请授权相关)(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
鸿蒙布道师1 天前
鸿蒙NEXT开发定位工具类 (WGS-84坐标系)(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
ghhgy5311 天前
已安装爱思助手和Apple相关驱动,但仍无法有线连接iPhone热点,且网络适配器没有Apple Mobile Device Ethernet,问题解决
ios·iphone
陈皮话梅糖@1 天前
iOS error: some files could not be transferred (code 23) at xxx
ios
林晨月2 天前
SwiftUI Color(一)
ios·swiftui
Andy3222 天前
030 期 3个神器让你的Mac更聪明!
ios·github·mac
iOS阿玮2 天前
“社交类的天塌了!”不是夸夸其谈而是确有其事!
ios·app·apple