当前位置:   article > 正文

Leetcode3218. 切蛋糕的最小总开销 I

Leetcode3218. 切蛋糕的最小总开销 I

Every day a Leetcode

题目来源:3218. 切蛋糕的最小总开销 I

解法1:记忆化搜索

对于两个数组horizontalCut和verticalCut,简称h和v,若v数组已经切了j次,则当切h[i]刀时,cost为h[i] * (j+1)。

很明显,要使总cost最小,对于两个数组,cost花费越大的那一行或者那一列,应该优先切除,因此先从大到小排序预处理。

代码:

#
# @lc app=leetcode.cn id=3218 lang=python3
#
# [3218] 切蛋糕的最小总开销 I
#

# @lc code=start
class Solution:
    def minimumCost(self, m: int, n: int, horizontalCut: List[int], verticalCut: List[int]) -> int:
        horizontalCut.sort(reverse=True)
        verticalCut.sort(reverse=True)

        m -= 1
        n -= 1
        @cache
        def dfs(i, j):
            if i == m and j == n:
                return 0
            if i == m:
                return dfs(i, j + 1) + verticalCut[j] * (i + 1)
            if j == n:
                return dfs(i + 1 , j) + horizontalCut[i] * (j + 1)
            
            return min(dfs(i, j + 1) + verticalCut[j] * (i + 1), dfs(i+ 1, j) + horizontalCut[i] * (j + 1))
        
        return dfs(0, 0)
# @lc code=end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(m2+n2+2*(m+n))。

空间复杂度:O(m2+n2+2*(m+n))。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/904087
推荐阅读
相关标签
  

闽ICP备14008679号