leetcode 546. Remove Boxes 很复杂的DP

来源:互联网 发布:日文游戏翻译软件 编辑:程序博客网 时间:2024/06/05 15:19

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 452. Minimum Number of Arrows to Burst Balloons 消除覆盖区间 很像

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

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>using namespace std;class Solution {public:    int removeBoxes(vector<int>& boxes)    {        const int n = boxes.size();        int dp[n][n][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 n == 0 ? 0 : dp[0][n - 1][0];    }};
原创粉丝点击