思路
01 背包问题
难点在于转化为背包问题;
代码
// 01背包问题
// 我想把石头尽可能分成重量相等的2堆
// f[i][j] : i块石头放进容量为j的背包里,装的最大价值
// f[i][j] = max(f[i-1][j], f[i-1][j- weights[i]] + values[i]);
// weights[i] = stones[i], values[i] = stones[i];
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int i, j;
int sum = 0, size = stones.size(), result = 0;
vector<vector<int>> f(size, vector<int>(3005, 0));
for(i = 0; i < size; i++)
{
sum += stones[i];
}
// 初始化
for(j = stones[0]; j <= sum; j++)
{
f[0][j] = stones[0];
}
for(i = 1; i < size; i++)
{
for(j = 1; j <= sum; j++)
{
if(j < stones[i])
{
f[i][j] = f[i-1][j];
}
else
{
f[i][j] = max(f[i-1][j], f[i-1][j - stones[i]] + stones[i]);
}
}
}
result = abs((sum - f[size-1][sum/2]) - f[size-1][sum/2]);
// cout << "sum/2 : " << f[size-1][sum/2] << ", sum : " << f[size-1][sum];
return result;
}
};