有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x
和 y
,且 x <= y
。那么粉碎的可能结果如下:
- 如果
x == y
,那么两块石头都会被完全粉碎; - 如果
x != y
,那么重量为x
的石头将会完全粉碎,而重量为y
的石头新重量为y-x
。
最后,最多只会剩下一块石头。返回此石头最小的可能重量。如果没有石头剩下,就返回 0
。
示例:
输入:[2,7,4,1,8,1] 输出:1 解释: 组合 2 和 4,得到 2,所以数组转化为 [2,7,1,8,1], 组合 7 和 8,得到 1,所以数组转化为 [2,1,1,1], 组合 2 和 1,得到 1,所以数组转化为 [1,1,1], 组合 1 和 1,得到 0,所以数组转化为 [1],这就是最优值。
提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
两个石头的重量越接近,粉碎后的新重量就越小。同样的,两堆石头的重量越接近,它们粉碎后的新重量也越小。
所以本题可以转换为,计算容量为 sum / 2
的背包最多能装多少石头。
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
s = sum(stones)
n = s // 2
dp = [False for i in range(n + 1)]
dp[0] = True
for stone in stones:
for j in range(n, stone - 1, -1):
dp[j] = dp[j] or dp[j - stone]
for j in range(n, -1, -1):
if dp[j]:
return s - j - j
class Solution {
public int lastStoneWeightII(int[] stones) {
int sum = 0;
for (int stone : stones) {
sum += stone;
}
int n = sum / 2;
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int stone : stones) {
for (int j = n; j >= stone; j--) {
dp[j] = dp[j] || dp[j - stone];
}
}
for (int j = n; ; j--) {
if (dp[j]) {
return sum - j - j;
}
}
}
}
func lastStoneWeightII(stones []int) int {
sum := 0
for _, stone := range stones {
sum += stone
}
n := sum / 2
dp := make([]bool, n+1)
dp[0] = true
for _, stone := range stones {
for j := n; j >= stone; j-- {
dp[j] = dp[j] || dp[j-stone]
}
}
for j := n; ; j-- {
if dp[j] {
return sum - j - j
}
}
}