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 1: 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. Note:
1 <= k <= len(nums) <= 16. 0 < nums[i] < 10000.
Solution:
Assume sum is the sum of nums[] . The dfs process is to find a subset of nums[] which sum equals to sum/k. We use an array visited[] to record which element in nums[] is used. Each time when we get a cur_sum = sum/k, we will start from position 0 in nums[] to look up the elements that are not used yet and find another cur_sum = sum/k.
classSolution: defcanPartitionKSubsets(self, nums: List[int], k: int) -> bool: # backtracking # since we don't have to print the result, we could use visited array to note if an element is used in a subset total = sum(nums) if total == 0or total % k != 0: returnFalse visited = [0]* len(nums) defbacktrack(visited, nums, k, cur_sum, cur_num, start, target): if k == 1: # we call backtrack when it's able to make k subsets # when there're k-1 subsets existed, we don't have to calculate the last returnTrue if cur_sum == target and cur_num > 0: # successfully find a subset return backtrack(visited, nums, k-1, 0, 0, 0, target) for i in range(start, len(nums)): ifnot visited[i]: visited[i] = 1 if backtrack(visited, nums, k, cur_sum+nums[i], cur_num+1, i+1, target): returnTrue visited[i] = 0 returnFalse return backtrack(visited, nums, k, 0, 0, 0, total/k)