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
- Leedcode 19 Remove Boxes
- Remove Boxes
- LeedCode 之 Remove Element
- [leedcode]-- 27. Remove Element
- [LeedCode OJ]#19 Remove Nth Node From End of List
- 546. Remove Boxes
- LeetCode Week8: Remove boxes
- 546. Remove Boxes (HARD)
- [LeetCode] Remove Boxes
- leetcode-Remove Boxes
- Leetcode546. Remove Boxes
- leetcode 546. Remove Boxes
- [leetcode]546. Remove Boxes
- 546. Remove Boxes
- 546. Remove Boxes
- Leetcode546. Remove Boxes(Hard)
- [LeedCode OJ]#27 Remove Element
- leedcode:remove duplicates from sorted list
- 队列和栈
- 针对不同浏览器预览上传文件的处理方式
- C# 基础知识系列]专题六:.net WinForm 控件的事件委托剖析
- 云计算:为什么说存储是云计算发展瓶颈之一?虚拟化是解决之道!
- redis桌面管理工具 redis-desktop-manager使用指南
- Leedcode 19 Remove Boxes
- 51 C语言与汇编语言混编
- stm32 can基础测试例程
- #python学习笔记#使用python爬取拉勾网职位信息(二):爬取数据
- form标签和其内部的button标签的关系
- 《Effective C++》第七章:模板与泛型编程
- Android 中的MVC模式
- Java 模拟登录新浪微博(Cookie)
- 搭建百万级别邮件发送平台