546. Remove Boxes

2020/12/20 leetcode 共 933 字,约 3 分钟

title

problem link

Given several boxes with different colors represented by different positive numbers. You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k points. Find the maximum points you can get.

Example 1:

Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Explanation:
[1, 3, 2, 2, 2, 3, 4, 3, 1] 
----> [1, 3, 3, 4, 3, 1] (3*3=9 points) 
----> [1, 3, 3, 3, 1] (1*1=1 points) 
----> [1, 1] (3*3=9 points) 
----> [] (2*2=4 points)

Constraints:

  • 1 <= boxes.length <= 100
  • 1 <= boxes[i] <= 100

给出几个不同颜色的箱子,用不同的正数表示。 你可能会经历几轮拆除箱子,直到没有箱子为止。

solution

参考

class Solution:
    def removeBoxes(self, boxes: List[int]) -> int:
        memo = {}

        def f(i, j, k):
            if i > j:
                return 0
            if (i, j, k) in memo:
                return memo.get((i, j, k))
            while i + 1 < j and boxes[i + 1] == boxes[i]:
                i += 1
                k += 1
            res = (1 + k) * (1 + k) + f(i + 1, j, 0)
            for m in range(i + 1, j + 1):
                if boxes[m] == boxes[i]:
                    res = max(res, f(i + 1, m - 1, 0) + f(m, j, 1 + k))
            memo[(i, j, k)] = res
            return res
        return f(0, len(boxes) - 1, 0)

Search

    Table of Contents