1049. 最后一块石头的重量 II
将题目转换为,把一堆石头分成两堆,求两堆石头重量差最小值
所以只要求将一堆stone放进最大容量为sum/2的背包,求放进去的石头的最大重量,记为MaxWeight,则另一堆石头的重量为sum-MaxWeight,最终答案即为sum-2*MaxWeight;、
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
vector<int> dp(15001, 0);
int sum = 0;
for (int stone:stones) sum += stone;
int target = sum / 2;
for (int stone:stones) { // 遍历物品
for (int j = target; j >= stone; j--) { // 遍历背包
dp[j] = max(dp[j], dp[j - stone] + stone);
}
}
return sum - dp[target] - dp[target];
}
};