算法刷题记录 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;
    }
};
相关推荐
MATLAB代码顾问8 分钟前
【智能优化】鹈鹕优化算法(POA)原理与Python实现
开发语言·python·算法
AI科技星24 分钟前
微积分:变化与累积的数学(分层大白话解释版)
人工智能·算法·数学建模·数据挖掘·机器人
sinat_2869451928 分钟前
llm wiki
人工智能·算法·chatgpt
xieliyu.31 分钟前
Java手搓二叉树:基础遍历与核心操作全解析
java·开发语言·数据结构·学习
期待のcode39 分钟前
Redis数据类型
运维·数据结构·redis
博界IT精灵1 小时前
图的遍历(哈喜老师)
数据结构·考研·算法·深度优先
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.05.10 题目:2770. 达到末尾下标所需的最大跳跃次数
笔记·算法·leetcode
Halo_tjn1 小时前
基于异常处理机制 相关知识点
java·开发语言·算法
xingyuzhisuan1 小时前
适合微调Llama 3 70B模型的最低GPU配置推荐
运维·人工智能·算法·llama·gpu算力
IJCAST2 小时前
Exploring the Frontiers of Complexity: Latest Research from IJCAST
人工智能·深度学习·神经网络·算法