c++ 3ms recursive solution


  • 0
    I
    class Solution {
    public:
        bool getSum(vector<int>& nums, int sum, int start)
        {
            for(int i = start; i >= 0; --i)
            {
               if(nums[i] == sum)
                 return true;
               if(nums[i] > sum)
                 continue;
               if(getSum(nums,sum-nums[i],i-1))
                 return true;
            }
            return false;
        }
        bool canPartition(vector<int>& nums) {
            int sum = 0;
            int n = nums.size();
            if(!n)
               return true;
            for(int i = 0; i < n; ++i)
              sum += nums[i];
            if(sum%2)
               return false;
            sort(nums.begin(),nums.end());
            return getSum(nums,sum/2,n-1);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.