动态规划(两个01背包)
【问题转化】:让⽯头分成重量相同的两堆,相撞之后剩下的⽯头最⼩,即成01背包问题
代码语言:javascript复制背包1 - 背包2 = (sum - 背包2) - 背包2
代码语言:javascript复制class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int size = stones.size();
int sum = accumulate(stones.begin(), stones.end(), 0);
int halfSum = sum / 2;
vector<int> dp(halfSum 1, 0);
for (int i = 0; i < size; i )
for (int j = halfSum; j >= stones[i]; j--)
dp[j] = max(dp[j], dp[j - stones[i]] stones[i]);
// 背包1 - 背包2 = (sum - 背包2) - 背包2 [不论sum是否偶数,均可解决]
return (sum - dp[halfSum]) - dp[halfSum];
}
};