LeetCode每日一题(546. Remove Boxes)

You are 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 (i.e., composed of k boxes, k >= 1), remove them and get k * k points.

Return 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] (33=9 points)
----> [1, 3, 3, 3, 1] (1
1=1 points)
----> [1, 1] (33=9 points)
----> [] (2
2=4 points)

Example 2:

Input: boxes = [1,1,1]
Output: 9

Example 3:

Input: boxes = [1]
Output: 1

Constraints:

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

讲解原文在这里, 建议大家一定要看一下。

假设 dp(i, j, k)为 boxes[i]左侧有 k 个相同颜色的盒子时消除 boxes[i]到 boxes[j]之间所有的盒子所能得到的最高分, 那面对 boxes[i]的时候, 我们会遇到两种情况, 一种是我们直接消除 boxes[i]及其左侧的相同颜色的盒子, 然后计算后面的 boxes[i+1]到 boxes[j]的消除分数, 即(k + 1) * (k + 1) + dp(i + 1, j, 0)。另一种是我们将 boxes[i]及其左侧相同颜色色盒子与 boxes[i+1…=j]中与 boxes[i]颜色相同的盒子合并消除, 假设与 boxes[i]颜色相同的盒子为 boxes[m], 则该情况为, dp(i+1, m-1, 0) + dp(m, j, k+1)



impl Solution {
    fn dp(boxes: &[i32], mut i: usize, j: usize, mut k: usize, cache: &mut Vec<Vec<Vec<i32>>>) -> i32 {
        if i > j {
            return 0;
        }
        if cache[i][j][k] > 0 {
            return cache[i][j][k];
        }
        let (i0, k0) = (i, k);
        while i < j && boxes[i] == boxes[i + 1] {
            i += 1;
            k += 1;
        }
        let mut ans = ((k + 1) * (k + 1)) as i32 + Solution::dp(boxes, i + 1, j, 0, cache);
        for m in i + 1..=j {
            if boxes[m] == boxes[i] {
                let next = Solution::dp(boxes, i + 1, m - 1, 0, cache) + Solution::dp(boxes, m, j, k + 1, cache);
                ans = ans.max(next);
            }
        }
        cache[i0][j][k0] = ans;
        ans
    }

    pub fn remove_boxes(boxes: Vec<i32>) -> i32 {
        Solution::dp(&boxes, 0, boxes.len() - 1, 0, &mut vec![vec![vec![0; boxes.len()]; boxes.len()]; boxes.len()])
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值