Python LeetCode(五)
不同的做法
优化
1. 546. Remove Boxes
class Solution(object):
result = 0
def recursive(self, boxes, cur):
l = len(boxes)
if l == 0:
if cur > self.result:
self.result = cur
return
elif l == 1:
if cur + 1 > self.result:
self.result = cur + 1
return
i = 0
while i < l:
if boxes[i] == boxes[i + 1]:
j = i
while j + 1 < l and boxes[j] == boxes[j + 1]:
j += 1
self.recursive(boxes[:i] + boxes[j + 1:], cur + pow(j - i + 1, 2))
i = j + 1
else:
self.recursive(boxes[:i] + boxes[i + 1:], cur + 1)
def removeBoxes(self, boxes):
"""
:type boxes: List[int]
:rtype: int
"""
self.recursive(boxes, 0)
return self.result
import collections
class Solution(object):
result = 0
def resetDict(self, boxes):
d = collections.defaultdict(int)
l = len(boxes)
i = 0
while i < l:
if i + 1 < l and boxes[i] == boxes[i + 1]:
j = i
while j + 1 < l and boxes[j] == boxes[j + 1]:
j += 1
d[i] = j - i + 1
i = j
else:
d[i] = 1
i+=1
return d
def recursive(self, boxes, cur):
l = len(boxes)
if l == 0:
if cur > self.result:
self.result = cur
return
elif l == 1:
if cur+1 > self.result:
self.result = cur+1
return
d = self.resetDict(boxes)
s = sorted(d.keys(), key=lambda x: d[x], reverse=True)
if d[s[0]] == d[s[len(s)-1]]:
a = collections.Counter()
for x in boxes:
a[x]+=1
s = sorted(d.keys(), key=lambda x:a[boxes[x]])
for i in s:
self.recursive(boxes[:i] + boxes[i + d[i]:], cur+pow(d[i], 2))
def removeBoxes(self, boxes):
"""
:type boxes: List[int]
:rtype: int
"""
self.recursive(boxes, 0)
return self.result
class Solution(object):
def removeBoxes(self, boxes):
"""
:type boxes: List[int]
:rtype: int
"""
self.color, self.length = [], []
for box in boxes:
if self.color and self.color[-1] == box:
self.length[-1] += 1
else:
self.color.append(box)
self.length.append(1)
M, N = len(self.color), len(boxes)
self.dp = [[[0] * N for x in range(M)] for y in range(M)]
return self.solve(0, M - 1, 0)
def solve(self, l, r, k):
if l > r: return 0
if self.dp[l][r][k]: return self.dp[l][r][k]
points = self.solve(l, r - 1, 0) + (self.length[r] + k) ** 2
for i in range(l, r):
if self.color[i] == self.color[r]:
points = max(points, self.solve(l, i, self.length[r] + k) + self.solve(i + 1, r - 1, 0))
self.dp[l][r][k] = points
return points
不知道怎么做
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号