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];
    }
};
相关推荐
王老师青少年编程6 小时前
2025年【江苏“信息与未来”编程思维】真题及题解(T2:坐标变换)
c++·题解·真题·坐标变换·编程思维·江苏·信息与未来
海石9 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石9 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
2023自学中10 小时前
C++ 内存追踪器
linux·c++
退休倒计时13 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
tachibana213 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode
兰令水13 小时前
leecodecode【面试150】【2026.7.9打卡-java版本】
java·数据结构·leetcode·面试·职场和发展
DogDaoDao14 小时前
【GitHub】 LLVM Project 深度解析:现代编译器基础设施的基石
java·c++·python·程序员·github·编译器·llvm
KuaCpp14 小时前
C++进程(下)
c++
来一碗刘肉面15 小时前
C++中的引用语法
c++·算法