C++ | Leetcode C++题解之第416题分割等和子集

题目:

题解:

cpp 复制代码
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int n = nums.size();
        if (n < 2) {
            return false;
        }
        int sum = 0, maxNum = 0;
        for (auto& num : nums) {
            sum += num;
            maxNum = max(maxNum, num);
        }
        if (sum & 1) {
            return false;
        }
        int target = sum / 2;
        if (maxNum > target) {
            return false;
        }
        vector<int> dp(target + 1, 0);
        dp[0] = true;
        for (int i = 0; i < n; i++) {
            int num = nums[i];
            for (int j = target; j >= num; --j) {
                dp[j] |= dp[j - num];
            }
        }
        return dp[target];
    }
};
相关推荐
程小k5 分钟前
C++设计模式
c语言·c++
软行23 分钟前
LeetCode 每日一题 166. 分数到小数
数据结构·c++·算法·leetcode·哈希算法
阿昭L24 分钟前
leetcode合并有序链表
leetcode·链表
SunkingYang29 分钟前
C++变量与函数命名规范技术指南 (基于华为编码规范与现代C++最佳实践)
c++·华为·编码规范·命名规则·命名规范·函数名字·成员变量
Tisfy34 分钟前
LeetCode 3461.判断操作后字符串中的数字是否相等 I:简单题简单做的时候到了
leetcode·题解·模拟·1024程序员节
夜晚中的人海36 分钟前
【C++】二分查找算法习题
开发语言·c++·算法
nju_spy39 分钟前
力扣每日一题(三)划分题 + 思路题
数学·算法·leetcode·动态规划·笔试·记忆化搜索·状态压缩
sulikey2 小时前
【C++ STL 深入解析】insert 与 emplace 的区别与联系(以 multimap 为例)
开发语言·c++·stl·stl容器·insert·emplace
fqbqrr2 小时前
2510C++,rest_rpc
c++·rpc