Description
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
- If x == y, both stones are totally destroyed;
- If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value.
Note:
- 1 <= stones.length <= 30
- 1 <= stones[i] <= 100
分析
题目的意思是:给你一个数组,做消消乐,剩下的数是两数值差,求最后剩下的最小的值。这道题的解法很特别,无论最后是怎么得到最小值, 每个数字都是对应了固定的符号,考虑 A 是所有正号的集合, B 是所有负号的集合, 那么 |A| + |B| = sum_all,并且 |A| - |B| >=0,所以 sum_all - 2|B| >=0,即|B| <= sum_all / 2,瞬间就变成了 0, 1 背包的 问题, 在sum_all / 2的容量下, 求|B|的最大值
dp[j]数组表示的是背包容量为j, 每个石头拿起来或者不拿起来,能装下最多的石头重量是多少
将石头分成两堆,不断缩小两堆石头重量的差值,最小差值即为最小剩余重量
- 当两堆石头重量相等时,剩余为0
- 当两队石头重量不相等时,不断缩小缩小两堆石头重量的差值,两堆石头中一定存在一堆重量小于sum/2(sum表示所有石头重量总和)
- 想0-1背包问题dp[k][i] 表示使用k个物品,背包容量为i的最大价值
- 对应到本题,两堆石头中一定存在一堆重量小于sum/2表示要找的一堆石头
- dp[k][i] 表示使用k个物品(石头),背包容量(一堆石头重量的极限值)为i的最大价值(一堆石头最大重量,但不大于i)
代码
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
n=len(stones)
sums=sum(stones)
dp=[0]*(sums//2+1)
for i in range(n):
for j in range(sums//2,stones[i]-1,-1):
dp[j]=max(dp[j],dp[j-stones[i]]+stones[i])
return sums-2*dp[-1]