1049 Last Stone Weight II

题目

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 weight x is totally destroyed, and the stone of weight y has new weight y-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的用法

  1. Set 没有操作符号[]
  2. set 插入使用insert函数
  3. dp状态转移要优先想到set

题目思路

  1. 自己以为不是每个数字符号的加减,+3-(7-8)等价于+3+7+8, 所以无论最后是怎么得到最小值, 每个数字都是对应了固定的符号

01背包思路

  1. 考虑 A 是所有正号的集合, B 是所有符号的集合, 那么 |A| + |B| = sum_all
  2. 并且 |A| - |B| >=0,
  3. 所以 sum_all - 2|B| >=0
  4. 所有 |B| <= sum_all / 2
  5. 瞬间就变成了 0, 1 背包的 问题, 在sum_all / 2的容量下, 求|B|的最大值
  6. bi 是容量值, 也是价值

DP思路

  1. 当前已计算出来所有的可能的和, 记录在set中, 用vector会tle
  2. 更新所有的可能和, 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值