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];
    }
};
相关推荐
所以遗憾是什么呢?9 分钟前
【题解】Educational Codeforces Round 195 (Rated for Div. 2) ABCDE
c++·动态规划·acm·icpc·ccpc·xcpc·codeforecs
Lhan.zzZ2 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
sysu_chenxy3 小时前
二重循环输出二维图形
c++
Navigator_Z3 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2084 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2084 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
划破黑暗的第一缕曙光5 小时前
[C++]:2.类和对象(下)
c++·类和对象·对象·类
Nil2085 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
lvwangshu6 小时前
川剧复演 题解
动态规划·题解·技巧·性质题·思维好题
黎相思6 小时前
LRU Cache
c++·缓存