Partition Equal Subset Sum Program (Leetcode)

Partition Equal Subset Sum Program (Leetcode):

Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

 

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

total = sum(nums)
if total & 1 == 1:
     return False

def subset(nums, index, target):
     if target == 0:
          return True

     if target < 0 or index == len(nums):
          return False

     if subset(nums, index + 1, target - nums[index]):
          return True
            
     i = index + 1
     while i < len(nums) and nums[i] == nums[index]: 
     #100 100 100 ... multiple times
          i += 1
     
return subset(nums, i, target)

print(subset(nums, 0, total // 2))  
#total // 2 because for 2 subset, sum must be half.

This program is similar to Combination Sum 2 or Sum of Subset.


Post a Comment

0 Comments