leetcode 546. Remove Boxes 删除箱子获得最大的分数 + 很复杂的DP + z做不出来

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:

[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)
Note: The number of boxes n would not exceed 100.

本题题意很简单,但是问题很复杂,不会做,所以参考了这个教程[LeetCode] Remove Boxes 移除盒子

感觉和这一道题leetcode 312. Burst Balloons 气球爆炸计算分数 + 一个按照length做动态规划DP的很棒的做法很像

暂时把答案放到这里吧,这道题必须好好学习

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>

using namespace std;


class Solution
{
public:
    int removeBoxes(vector<int>& boxes)
    {
        if (boxes.size() <= 0)
            return 0;

        int n = boxes.size();
        vector<vector<vector<int>>> dp(n,vector<vector<int>>(n,vector<int>(n,0)));
        for (int i = 0; i < n; i++)
        {
            for (int k = 0; k <= i; k++)
            {
                dp[i][i][k] = (1 + k) * (1 + k);
            }
        }

        for (int t = 1; t < n; t++)
        {
            for (int j = t; j < n; j++)
            {
                int i = j - t;
                for (int k = 0; k <= i; k++)
                {
                    int res = (1 + k) * (1 + k) + dp[i + 1][j][0];
                    for (int m = i + 1; m <= j; ++m)
                    {
                        if (boxes[m] == boxes[i])
                        {
                            res = max(res, dp[i + 1][m - 1][0] + dp[m][j][k + 1]);
                        }
                    }
                    dp[i][j][k] = res;
                }
            }
        }
        return dp[0][n - 1][0];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值