[leetcode] 1049. Last Stone Weight II

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. 1 <= stones.length <= 30
  2. 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]

参考文献

[LeetCode] [Java/C++/Python] Easy Knapsacks DP
问题转化为0-1背包求解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值