416. Partition Equal Subset Sum

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了416. Partition Equal Subset Sum相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/partition-equal-subset-sum/description/

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int s = 0;
        for (auto i : nums) s+= i;
        if (s == 0 || s % 2 != 0)     return false;
        
        // sort nums in desc order, and hopefully we will find the result more quickly.
        sort(nums.begin(), nums.end(), [](int a, int b) {return a > b;});
        return helper(nums, s/2, s/2, 0);
    }
    // nums[start] will be put in set1/remain1, or set2/remain2
    bool helper(vector<int>& nums, int remain1, int remain2, int start) {
        // we found a solution
        if (remain1 == nums[start] || remain2 == nums[start])   return true;
        // try to put in set1
        if (remain1 > nums[start] && helper(nums, remain1-nums[start], remain2, start+1))
            return true;
        // try to put in set2
        if (remain2 > nums[start] && helper(nums, remain1, remain2-nums[start], start+1))
            return true;
        // otherwise, we fail
        return false;
    }
};

 

以上是关于416. Partition Equal Subset Sum的主要内容,如果未能解决你的问题,请参考以下文章

LN : leetcode 416 Partition Equal Subset Sum

416. Partition Equal Subset Sum

416. Partition Equal Subset Sum

Leetcode 416. Partition Equal Subset Sum

416. Partition Equal Subset Sum

算法: 等分子集总和416. Partition Equal Subset Sum