LC.P698[划分为k个相等的子集]

方法一:回溯+剪枝

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
class Solution {

int[] nums;
boolean[] visited;
int n, target, k;

public boolean canPartitionKSubsets(int[] nums, int k) {
int total = 0;
for (int num : nums) total += num;
if (total % k != 0) return false;
this.nums = nums;
n = nums.length;
this.k = k;
Arrays.sort(nums);
visited = new boolean[n];
target = total / k;
return dfs(n - 1, 0, 0);
}

private boolean dfs(int idx, int cur, int cnt) {
if (cnt == k) return true;
if (cur == target) return dfs(n - 1, 0, cnt + 1);
for (int i = idx; i >= 0; --i) {
if (visited[i] || cur + nums[i] > target) continue;
visited[i] = true;
if (dfs(i - 1, cur + nums[i], cnt)) return true;
visited[i] = false;
if (cur == 0) return false;
}
return false;
}
}