Partition to K Equal Sum Subsets
Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into k non-empty subsets whose sums are all equal.
Example
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It’s possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Solution
看别人说DP用bitmasking做,但暂时没太看明白
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
def dfs(index):
if index==len(nums):
return len(set(buck))== 1
for i in range(k):
print('i=%d'%(i),'index=%d'%(index))
print(buck[i])
buck[i] += nums[index]
print(buck[i])
if buck[i]<= nsum//k and dfs(index+1):
return True
buck[i] -= nums[index]
if buck[i]==0:
break
return False
nums.sort(reverse=True)
nsum = sum(nums)
if nsum%k != 0:
return False
if nums[0] > nsum//k:
return False
buck = [0]*k
return dfs(0)