当前位置: 代码迷 >> 综合 >> 【刷题喽】移除盒子
  详细解决方案

【刷题喽】移除盒子

热度:77   发布时间:2024-02-11 16:14:47.0

546. 移除盒子

难度困难225收藏分享切换为英文关注反馈

给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。
你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k*k 个积分。
当你将所有盒子都去掉之后,求你能获得的最大积分和。

 

示例:

输入:boxes = [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 分) 
----> [1, 3, 3, 3, 1] (1*1=1 分) 
----> [1, 1] (3*3=9 分) 
----> [] (2*2=4 分)
import collections
class Solution(object):def removeBoxes(self, boxes):if len(boxes)==1:return 1score=0temp=0for i in range(len(boxes)):for j in range(i,len(boxes)):if boxes[i]!=boxes[j]:newArr=boxes[:i]+boxes[j:]temp=pow((j-i),2)+self.removeBoxes(newArr)breakif temp==0:temp=pow((j-i+1),2)if temp>score:score=tempreturn score

暴力递归,哈哈!

整个ij来应对连续的问题

比如【1,1,2,3】:

首先 2*2+removeBoxes(【2,3】)

1*1+removeBoxes(【1,1,3】)

1*1 +removeBoxes(【1,1,2】)

。。。

设置temp==0是因为碰到【2,2,2】连续的数组的时候

  相关解决方案