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
. -
- 思路:之前dfs大多是要求累加和等于一个数
* 现在这里是要求累加和等于多个相同的数
* 套路还是一样的,之前是维护一个变量,现在变成维护一个数组而已
* 就在每次dfs的时候填到相应的坑就好了 -
- 类似于http://blog.csdn.net/zjucor/article/details/76714230
-
package l698; import java.util.Arrays; /* * 之前dfs大多是要求累加和等于一个数 * 现在这里是要求累加和等于多个相同的数 * 套路还是一样的,之前是维护一个变量,现在变成维护一个数组而已 * 就在每次dfs的时候填到相应的坑就好了 */ class Solution { int[] ret; boolean f = false; public boolean canPartitionKSubsets(int[] nums, int k) { Arrays.sort(nums); int sum = 0; int[] a = new int[nums.length]; for(int i=0; i<nums.length; i++) { a[i] = nums[nums.length-1-i]; sum += a[i]; } if(sum % k != 0) return false; for(int i : a) if(i > sum/k) return false; ret = new int[k]; dfs(a, sum/k, 0); return f; } private void dfs(int[] a, int target, int s) { if(f) return; if(s == a.length) { for(int i=0; i<ret.length; i++) if(ret[i] != target) return; f = true; return; } for(int i=0; i<ret.length; i++) { if(ret[i] + a[s] <= target) { ret[i] += a[s]; dfs(a, target, s+1); ret[i] -= a[s]; } } } }
''' same algorithm AC in Java, TLE in Python ''' class Solution(object): f = False; def dfs(self, nums, start, k, ret, target): if self.f: return if start == len(nums): for i in range(k): if ret[i] != target: return self.f = True return for i in range(k): if ret[i]+nums[start]<=target: ret[i] += nums[start] self.dfs(nums, start+1, k, ret, target) ret[i] -= nums[start] def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if k==1: return True s = sum(nums) if s%k: return False target = s / k for i in nums: if i>target: return False nums.sort(reverse=True) self.dfs(nums, 0, k, [0]*k, target) return self.f print() s = Solution() #print(s.canPartitionKSubsets([4, 3, 2, 3, 5, 2, 1], 4)) #print(s.canPartitionKSubsets([5,2,5,5,5,5,5,5,5,5,5,5,5,5,5,3], 15)) print(s.canPartitionKSubsets([7628, 3147, 7137, 2578, 7742, 2746, 4264, 7704, 9532, 9679, 8963, 3223, 2133, 7792, 5911, 3979], 6))