Skip to content

Commit f05a165

Browse files
committed
Partition Equal Subset Sum
1 parent 8514064 commit f05a165

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

partition_equal_subset_sum.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# https://www.lintcode.com/problem/partition-equal-subset-sum/description
2+
3+
# Given a non-empty array containing only positive integers,
4+
# find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
5+
#
6+
# Example:
7+
# Input: nums = [1, 5, 11, 5],
8+
# Output: true
9+
# Explanation:
10+
# two subsets: [1, 5, 5], [11]
11+
12+
"""
13+
>>> Solution().canPartition([1, 5, 11, 5])
14+
True
15+
>>> Solution().canPartition([1, 2, 3, 9])
16+
False
17+
>>> Solution().canPartition([1, 4, 5, 6, 1, 32, 4, 1, 3, 4, 5, 5, 5, 5, 1, 2, 4, 5, 1])
18+
True
19+
"""
20+
21+
22+
class Solution:
23+
"""
24+
@param nums: a non-empty array only positive integers
25+
@return: true if can partition or false
26+
"""
27+
28+
def canPartition(self, nums):
29+
memo = dict()
30+
total = sum(nums)
31+
if total % 2 != 0:
32+
return False
33+
return self._canPartition(nums, 0, 0, total, memo)
34+
35+
def _canPartition(self, nums, index, partial_sum, total, memo):
36+
current = f'{index}_{partial_sum}'
37+
if current in memo:
38+
return memo[current]
39+
if partial_sum * 2 == total:
40+
return True
41+
elif partial_sum > total // 2 or index >= len(nums):
42+
return False
43+
without_get_number = self._canPartition(nums, index + 1, partial_sum, total, memo)
44+
get_number = self._canPartition(nums, index + 1, partial_sum + nums[index], total, memo)
45+
memo[current] = without_get_number or get_number
46+
return memo[current]

0 commit comments

Comments
 (0)