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:
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)
代码
参考文献
[LeetCode] [Java/C++/Python] Easy Knapsacks DP问题转化为0-1背包求解