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];
    }
};
相关推荐
Teleger1 小时前
在window上使用c++控制鼠标点击,实现的exe
c++·单片机·计算机外设
如竟没有火炬2 小时前
接雨水22
数据结构·python·算法·leetcode·散列表
June`3 小时前
高并发内存池如何实现
c++·tcmalloc·内存池
ComputerInBook3 小时前
C++ 关键字 constexpr 和 consteval 之注意事项
开发语言·c++·constexpr·consteval
米啦啦.3 小时前
STL(标准模板库)
开发语言·c++·stl
咩咦3 小时前
C++学习笔记08:指针和引用的区别
c++·学习笔记·指针·引用·指针和引用
洛水水3 小时前
【力扣100题】34.二叉搜索树中第K小的元素
c++·算法·leetcode
_深海凉_3 小时前
LeetCode热题100-翻转二叉树
算法·leetcode·职场和发展
许长安3 小时前
gRPC Keepalive 机制
c++·经验分享·笔记·rpc
wangjialelele4 小时前
Linux SystemV 消息队列 + 责任链模式:实现客户端消息处理流水线
linux·服务器·c语言·网络·c++·责任链模式