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];
}
};