算法刷题记录 Day36

算法刷题记录 Day36

Date: 2024.04.02

lc 416. 分割等和子集

c++ 复制代码
//2. 一维数组
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        // 将问题转化为从数组中任意取数,使得容量为数组总和一半的背包内的价值尽可能大。
        // dp[j]表示容积为j的背包中,能装的最大价值。
        // dp[j] = for(int i=n-1; i>=0; i++) max(dp[j], dp[j-nums[i]]+nums[i]);

        int n = nums.size();
        int count = 0;
        for(auto& x: nums){
            count += x;
        }
        int half_count = count / 2;

        vector<int> dp(half_count+1, 0);

        for(int i=0; i<n; i++){
            for(int j=half_count; j>=nums[i]; j--){
                dp[j] = max(dp[j], dp[j-nums[i]]+nums[i]);
            }
        }

        if(dp[half_count] == (count - half_count))
            return true;
        else
            return false;

        
    }
};

// 1. 二维数组
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        // 将问题转化为从数组中任意取数,使得容量为数组总和一半的背包内的价值尽可能大。
        // dp[i][j] 表示从第[0, i]个数中,容积为j的背包的最大价值;
        // dp[i][j] = max(dp[i-1][j], dp[i-1][j-v[i]]+v[i]);
        // 初始化第一行中,j大于等于nums[0]的为j,其余为0;
        int n = nums.size();
        int count = 0;
        for(auto& x: nums){
            count += x;
        }
        int half_count = count / 2;

        vector<vector<int>> dp(n, vector<int>(half_count+1, 0));
        for(int j=nums[0]; j<=half_count; j++){
            dp[0][j] = nums[0];
        }

        for(int i=1; i<n; i++){
            for(int j=0; j<=half_count; j++){
                if(j < nums[i])
                    dp[i][j] = dp[i-1][j];
                else{
                    dp[i][j] = max(dp[i-1][j], dp[i-1][j-nums[i]]+nums[i]);
                }
            }
        }

        // for(int i=0; i<n; i++){
        //     for(int j=0; j<=half_count; j++){
        //         cout<<"i:"<<i<<", j:"<<j<<", value:"<<dp[i][j]<<endl;
        //     }
        // }

        if(dp[n-1][half_count] == (count - half_count))
            return true;
        else
            return false;
    }
};
相关推荐
roman_日积跬步-终至千里6 分钟前
【计算机算法与设计(10)】习题:苹果买卖问题——分治法的经典应用
算法
deepdata_cn14 分钟前
模型预测控制(MPC)算法
算法
独自破碎E19 分钟前
如何用最短替换让字符串变平衡?
java·开发语言·算法·leetcode
Jasmine_llq33 分钟前
《P1082 [NOIP 2012 提高组] 同余方程》
算法·数学建模·质因数分解(试除法)·快速幂(模幂运算)·欧拉函数计算·基于质因数分解
算家计算36 分钟前
AI真的懂你!阿里发布Qwen3-Omni-Flash 全模态大模型:超强交互,人设任选
人工智能·算法·机器学习
l1t37 分钟前
利用Duckdb求解Advent of Code 2025第9题 最大矩形面积
数据库·sql·算法·duckdb·advent of code
Swift社区37 分钟前
LeetCode 446 - 等差数列划分 II - 子序列
算法·leetcode·职场和发展
CS创新实验室1 小时前
计算机考研408【数据结构】核心知识点总结
数据结构·考研·计算机·408
hetao17338371 小时前
2025-12-10 hetao1733837的刷题笔记
c++·笔记·算法
步达硬件1 小时前
【matlab】代码库-一维线性插值
数据结构·算法·matlab