题目
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 weightx
is totally destroyed, and the stone of weighty
has new weighty-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:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value.
小结
set的用法
- Set 没有操作符号[]
- set 插入使用insert函数
- dp状态转移要优先想到set
题目思路
- 自己以为不是每个数字符号的加减,+3-(7-8)等价于+3+7+8, 所以无论最后是怎么得到最小值, 每个数字都是对应了固定的符号
01背包思路
- 考虑 A 是所有正号的集合, B 是所有符号的集合, 那么 |A| + |B| = sum_all
- 并且 |A| - |B| >=0,
- 所以 sum_all - 2|B| >=0
- 所有 |B| <= sum_all / 2
- 瞬间就变成了 0, 1 背包的 问题, 在sum_all / 2的容量下, 求|B|的最大值
- bi 是容量值, 也是价值
DP思路
- 当前已计算出来所有的可能的和, 记录在set中, 用vector会tle
- 更新所有的可能和, set[i] + cur_num ,或者set[i] - cur_num
code1 01背包
int lastStoneWeightII(vector<int>& stones) {
int sumA=0;
bitset<15001> f(0);
f[0] = 1;
int sum_all = 0;
for(const auto& stone : stones){
sum_all += stone;
for(int j=15001; j>=stone; j--){
f[j] = f[j] | f[j-stone];
}
}
for(int j = sum_all / 2; j>=0; j--){
if(f[j]){
return sum_all - j - j;
}
}
return -1;
}
code2 DP
int lastStoneWeightII(vector<int>& stones) {
set<int> sum_a;
set<int> sum_b;
sum_a.insert(0);
for(const int &stone : stones){
sum_b.clear();
for(const auto& cur_sum : sum_a){
sum_b.insert(cur_sum - stone);
sum_b.insert(cur_sum + stone);
}
sum_a = sum_b;
}
int ans = 0x3f3f3f3f;
for(const int &a : sum_a){
ans = min(ans, a);
}
return ans;
}