Given an array of integersnumsand a positive integerk, find whether it's possible to divide this array intoknon-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.
b. 当curSum等于target时,我们找到一个符合条件的group, 下一步就是从数组的开头重头开始搜索符合的条件的下一个group
class Solution {
public boolean canPartitionKSubsets(int[] nums, int k) {
if (nums == null || nums.length <= k) {
return false;
}
int sum = 0;
for (int num : nums) {
sum += num;
}
if (sum % k != 0) {
return false;
}
boolean[] used = new boolean[nums.length];
return canPartitionKSubsets(nums, k, sum / k, 0, 0, used);
}
public boolean canPartitionKSubsets(int[] nums, int group, int target, int start, int curSum, boolean[] used) {
// Only one group left, we can use the remaining numbers to form the subset
if (group == 1) {
return true;
}
// If current sum equals to target, we find a subset, restart the search from the beginning of nums to find the
// next valid subset
if (curSum == target) {
return canPartitionKSubsets(nums, group - 1, target, 0, 0, used);
}
for (int i = start; i < nums.length; i++) {
if (!used[i]) {
used[i] = true;
if (canPartitionKSubsets(nums, group, target, i + 1, curSum + nums[i], used)) {
return true;
}
used[i] = false;
}
}
return false;
}
}