LC每日一题|20240628 - 2742. 给墙壁刷油漆

87 阅读1分钟

LC每日一题|20240628 - 2742. 给墙壁刷油漆

给你两个长度为 n 下标从 0 开始的整数数组 cost 和 time ,分别表示给 n 堵不同的墙刷油漆需要的开销和时间。你有两名油漆匠:

  • 一位需要 付费 的油漆匠,刷第 i 堵墙需要花费 time[i] 单位的时间,开销为 cost[i] 单位的钱。
  • 一位 免费 的油漆匠,刷 任意 一堵墙的时间为 1 单位,开销为 0 。但是必须在付费油漆匠 工作 时,免费油漆匠才会工作。

请你返回刷完 n 堵墙最少开销为多少。

提示:

  • 1 <= cost.length <= 500
  • cost.length == time.length
  • 1 <= cost[i] <= 10^6
  • 1 <= time[i] <= 500

题目等级:Hard

解题思路

01背包

AC代码

class Solution {
    fun paintWalls(cost: IntArray, time: IntArray): Int {
        val map = HashMap<String, Long>()
        fun dfs(i: Int, j: Int): Long {
            if (i < j) return 0L
            if (i < 0) return Int.MAX_VALUE.toLong()
            if (map["$i:$j"] != null) return map["$i:$j"]!!
            return Math.min(dfs(i - 1, j + time[i]) + cost[i], dfs(i - 1, j - 1)).apply {
                map["$i:$j"] = this
            }
        }
        return dfs(cost.size - 1, 0).toInt()
    }    
}