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
    }
}

执行用时&内存分布

相关推荐
GitLqr11 小时前
Flutter 3.47 与 Dart 3.13:你必须了解的迁移指南
flutter·ios·dart
冯汉栩15 小时前
Swift Control View,Label渐变颜色(源码)
开发语言·ios·swift
jike_202618 小时前
iPhone日历查看会议纪要APP推荐:按日期查找历史录音更方便
ios·语音识别·iphone
冯汉栩1 天前
OC 技术 App上存蒲公英教程
ios
码云之上1 天前
小程序 iOS 多输入框焦点乱序脱坑记
ios·微信小程序·taro
2501_915909062 天前
iOS test 测试怎么做?功能、性能、兼容、稳定与安全五类测试指南
android·ios·小程序·https·uni-app·iphone·webview
随遇丿而安2 天前
第 1 周:别小看 `UILabel`,它跟 Android TextView 不只是名字不同
ios
游戏开发爱好者83 天前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
Anhty4 天前
2026 实测 4 款 AI 变声器|QQ 聊天伪装声线,告别僵硬假声
人工智能·功能测试·ios·智能手机·安卓
唔664 天前
flutter web iOS 在浏览器加载中文慢的问题
前端·flutter·ios