Given a non-empty array containing only positive integers, find if the array can is partitioned into Subsets such the sum of elements in both subsets is equal.
Note:
- Each of the array element would not be exceed 100.
- The array size would not be exceed 200.
Example 1:
Input: [1, 5, one, 5]output:trueexplanation:the array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]output:falseexplanation:the array cannot is partitioned into equal sum subsets.
Use DP to solve the subject. Dp[i] Indicates whether there is a subset that makes sum equal to I.
1 classsolution (object):2 defcanpartition (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:bool6 """7s =sum (nums)8 9 ifS% 2 = = 1:returnFalseTentarget = S/2 OneDP = [false]* (target+1) ADp[0] =True - - forIinchRange (len (nums)): the forJinchRange (target, nums[i]-1, 1): -DP[J] = Dp[j]orDp[j-Nums[i]] - - returnDp[target]
Another problem can be solved with a similar approach: given a list of positive integers and a target. Is there a subset that makes sum (subset) = target?
def subsetsum (Nums, target): = sum (nums) ifreturn False = [FALSE] * (target + 1) = True for in Range (len (nums)): A in range ( Target, Nums[i]-1,-1): or dp[j- nums[i] [ return Dp[target]
Leetcode 416. Partition Equal Subset Sum