【算法与数据结构】1049、LeetCode 最后一块石头的重量 II

文章目录

所有的LeetCode题解索引,可以看这篇文章------【算法和数据结构】LeetCode题解

一、题目

二、解法

思路分析:本题需要得到石头之间两两粉碎之后的最小值,那么一个简单的思路就是将这堆石头划分成大小相近的两小堆石头,然后粉碎,这样得到的结果必然是最优值。那么如何划分呢?我们可以将所有石头的质量求和,假设和为 s u m sum sum,以 s u m / 2 sum/2 sum/2为界限。一堆石头质量设为 w 1 w_1 w1,有 w 1 ≤ s u m / 2 w_1 \leq sum/2 w1≤sum/2;而另外一堆石头质量 w 2 w_2 w2,有 w 2 ≥ s u m / 2 w_2 \geq sum/2 w2≥sum/2,且 w 1 + w 2 = s u m w_1 + w_2=sum w1+w2=sum。因为要求两堆石头粉碎之后的质量 Δ \Delta Δ最小,所以划分出来的两堆石头重量越接近越好,等同于 w 1 w_1 w1和 w 2 w_2 w2越接近于 s u m / 2 sum/2 sum/2。所以我们可以将 m i n ( Δ = w 2 − w 1 ) min(\Delta =w_2- w_1) min(Δ=w2−w1)问题,转化为 m a x ( w 1 ) , s . t . w 1 ≤ s u m / 2 max(w_1), s.t. w_1 \leq sum/2 max(w1),s.t.w1≤sum/2,即在这个数组中找到和最接近sum/2的子集。这是一个01背包问题。最终的最小质量 Δ m i n = w 2 − w 1 = s u m − 2 ∗ w 1 \Delta_{min}= w_2- w_1 = sum - 2*w_1 Δmin=w2−w1=sum−2∗w1。

程序如下:

cpp 复制代码
class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int sum = accumulate(stones.begin(), stones.end(), 0);
        vector<int> dp(vector<int>(sum/2 + 1, 0));
        for (int i = 0; i < stones.size(); i++) {			// 遍历物品
            for (int j = sum/2; j >= stones[i]; j--) {			// 遍历背包容量
                dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return sum -2 * dp[sum/2];
    }
};

复杂度分析:

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)。
  • 空间复杂度: O ( n ) O(n) O(n)。

三、完整代码

cpp 复制代码
# include <iostream>
# include <vector>
# include <numeric>
# include <algorithm>
using namespace std;

class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int sum = accumulate(stones.begin(), stones.end(), 0);
        vector<int> dp(vector<int>(sum/2 + 1, 0));
        for (int i = 0; i < stones.size(); i++) {			// 遍历物品
            for (int j = sum/2; j >= stones[i]; j--) {			// 遍历背包容量
                dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return sum -2 * dp[sum/2];
    }
};

int main() {
    Solution s1;
    vector<int> stones = { 2,7,4,1,8,1 };
    int result = s1.lastStoneWeightII(stones);
    cout << result << endl;
    system("pause");
    return 0;
}

end

相关推荐
聚客AI16 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v19 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工20 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 天前
322:零钱兑换(三种方法)
算法
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法