-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubsetPartition.java
50 lines (38 loc) · 1.2 KB
/
SubsetPartition.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package org.sean.backtracking;
import java.util.Arrays;
/***
* 698. Partition to K Equal Sum Subsets
*/
public class SubsetPartition {
public boolean canPartitionKSubsets(int[] nums, int k) {
if (k == 1) return true;
int sum = Arrays.stream(nums).sum();
if (sum % k != 0)
return false;
int avg = sum / k;
Arrays.sort(nums);
int endIndex = nums.length - 1;
if (nums[endIndex] > avg)
return false;
// reduce the elements equal to avg
while (endIndex >= 0 && nums[endIndex] == avg) {
endIndex--;
k--;
}
return dfs(new int[k], nums, endIndex, avg);
}
private boolean dfs(int[] subSets, int[] nums, int index, int target) {
if (index < 0)
return true;
for (int i = 0; i < subSets.length; i++) {
// try to put elem into one of the subSets recursively
if (subSets[i] + nums[index] <= target) {
subSets[i] += nums[index];
if (dfs(subSets, nums, index - 1, target))
return true;
subSets[i] -= nums[index];
}
}
return false;
}
}