题目:
有一堆石头,每块石头的重量都是正整数。每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
解答:
法一:目标将石头分为两堆,其重量尽可能相同。
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
#将石头分成两堆,让其重量尽可能接近
total=sum(stones)
target=total//2
dp=[0]*(target+1)
#0-1背包
for stone in stones:
for j in range(target,-1,-1):
if j>=stone:
dp[j]=max(dp[j],dp[j-stone]+stone)
return total-2*dp[target]
法二:先对列表进行逆序排列,每次取出前两个元素进行比较,如果不等,则将其差值添加到列表末尾;然后删掉列表前两个元素。如果列表为空,则返回0,否则循环上述操作。
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
i=0
while i <len(stones)-1:
stones.sort(reverse=True)
t=stones[i]-stones[i+1]
if t!=0:
stones.append(t)
del stones[i:i+2]
if not stones:
return 0
else:
i=0
return stones[0]
法三:小根堆(python支持小根堆)
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# 初始化
heap = [-stone for stone in stones]
#heapify(x):以线性时间讲一个列表转化为堆
heapq.heapify(heap)
# 模拟
while len(heap) > 1:
x,y = heapq.heappop(heap),heapq.heappop(heap)
if x != y:
heapq.heappush(heap,x-y)
if heap:
return -heap[0]
else:
return 0