码迷,mamicode.com
首页 > 其他好文 > 详细

416. Partition Equal Subset Sum

时间:2018-05-11 14:36:46      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:desc   art   nbsp   set   begin   amp   The   solution   class   

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

标签:desc   art   nbsp   set   begin   amp   The   solution   class   

原文地址:https://www.cnblogs.com/JTechRoad/p/9024168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!