-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanPartitionKSubsets.java
More file actions
51 lines (36 loc) · 1.09 KB
/
canPartitionKSubsets.java
File metadata and controls
51 lines (36 loc) · 1.09 KB
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
51
class Solution {
public boolean canPartitionKSubsets(int[] nums, int k) {
int sum = 0;
for (int n : nums) sum += n;
if (sum % k != 0) return false;
int target = sum / k;
Arrays.sort(nums);
reverse(nums);
int[] bucket = new int[k];
return backtrack(nums, 0, bucket, target);
}
private boolean backtrack(int[] nums, int index, int[] bucket, int target) {
if (index == nums.length) {
return true;
}
int current = nums[index];
for (int i = 0; i < bucket.length; i++) {
if (bucket[i] + current > target) continue;
bucket[i] += current;
if (backtrack(nums, index + 1, bucket, target)) return true;
bucket[i] -= current;
if (bucket[i] == 0) break;
}
return false;
}
private void reverse(int[] nums) {
int i = 0, j = nums.length - 1;
while (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
}