Skip to content

Commit

Permalink
python: Create partition to k equal sum subsets.
Browse files Browse the repository at this point in the history
  • Loading branch information
rixant committed Jan 27, 2023
1 parent 7d8d654 commit 845a0c6
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions python/0698-partition-to-k-equal-sum-subsets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""

if sum(nums) % k != 0:
return False

nums.sort(reverse = True)
target = sum(nums) / k
visited= set()

def backtrack(idx, count, currSum):
if count == k:
return True

if target == currSum:
return backtrack(0, count + 1, 0)

for i in range(idx, len(nums)):

# skip duplicates if last same number was skipped
if i > 0 and (i - 1) not in visited and nums[i] == nums[i - 1]:
continue

if i in visited or currSum + nums[i] > target:
continue

visited.add(i)

if backtrack(i + 1, count, currSum + nums[i]):
return True

visited.remove(i)

return False


return backtrack(0, 0, 0)

0 comments on commit 845a0c6

Please sign in to comment.