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;
    }
};

 

转载于:https://www.cnblogs.com/JTechRoad/p/9024168.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值