forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
python: Create partition to k equal sum subsets.
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |