Leedcode 19 Remove Boxes

来源:互联网 发布:物流软件系统 编辑:程序博客网 时间:2024/06/06 12:23

1、题目描述
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.
尽量连续移除相同颜色箱子以得到更多分数,该题目利用数组中相同数值表示相同颜色的箱子。
使用一个例子详细说明题意:
输入 [1, 3, 2, 2, 2, 3, 4, 3, 1]
输出 23
过程解析
[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)
2、解题思路
果然是难度系数很高的题目,看得一脸懵,参考大神们的代码,才写出这段程序,下面讲一下解题的思路:
对于任何的boxes[l,r]子区间,只有知道左边有多少个元素与boxes[i]相等,这里用k表示,使用dpp[l][r][k]表示左边有k个元素与i元素相等时子区间i,j能够取得的最大分数,容易得到dpp[l][l][k]=(k+1)(k+1),移除i元素后,得到分数为dpp[l+1][r][k]+(k+1)(k+1),此外,当l,r元素之间存在i元素与l元素相等时,就先移除l+1到i-1之间的元素,得分变为dpp[l+1][i-1][0]+dpp[i][r][k+1]。
注意这里测试的时候dpp[100][100][100]会出现内存限制,但是LeetCode上测试就不会。
3、实现代码

class Solution {public:    int removeBoxes(vector<int>& boxes) {        int  n = boxes.size();        int  dpp[100][100][100] = { 0 };        return cpoint(0, n - 1, 0, dpp, boxes);    }    int cpoint(int l, int r, int k, int dpp[100][100][100], vector<int>& boxes){        if (l > r) return 0;        if (dpp[l][r][k] > 0) return dpp[l][r][k];        int hp = (k + 1)*(k + 1) + cpoint(l + 1, r, 0, dpp, boxes);        for (int i = l + 1; i <=r; i++){            if (boxes[l] == boxes[i]){                hp = max(hp, cpoint(l + 1, i - 1, 0, dpp, boxes) + cpoint(i, r, k + 1, dpp, boxes));            }        }        return  dpp[l][r][k] = hp;    }};

4、运行结果
Submission Details
60 / 60 test cases passed.
Status: Accepted
Runtime: 156 ms
Submitted: 0 minutes ago

原创粉丝点击