-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path[698]划分为k个相等的子集.java
54 lines (44 loc) · 1.06 KB
/
[698]划分为k个相等的子集.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
51
52
53
54
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canPartitionKSubsets(int[] nums, int k) {
if (k > nums.length) {
return false;
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res + nums[i];
}
if (res % k != 0) {
return false;
}
int target = res / k;
boolean[] used = new boolean[nums.length];
return backtrack(k, 0, nums, 0, used, target);
}
public boolean backtrack(int k, int bucket, int[] nums, int start, boolean[] used, int target) {
if (k == 0) {
return true;
}
if (bucket == target) {
return backtrack(k - 1, 0, nums, 0, used, target);
}
for (int i = start; i < nums.length; i++) {
if (used[i]) {
continue;
}
if (bucket + nums[i] > target) {
continue;
}
used[i] = true;
bucket = bucket + nums[i];
boolean f = backtrack(k, bucket, nums, i + 1, used, target);
if (f) {
return true;
}
used[i] = false;
bucket = bucket - nums[i];
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)