Problem
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-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.
Note:
1 <= k <= len(nums) <= 16.
0 < nums[i] < 10000.
Solution
```class Solution {
public boolean canPartitionKSubsets(int[] nums, int k) {
int sum = 0;
for (int num: nums) sum += num;
if (k == 0 || sum%k != 0 || sum < k) return false;
int target = sum/k;
return dfs(nums, new boolean[nums.length], 0, k, 0, target);
}
private boolean dfs(int[] nums, boolean[] used, int start, int k, int sum, int target) {
if (k == 1) return true;
if (sum == target) return dfs(nums, used, 0, k-1, 0, target);
for (int i = start; i < nums.length; i++) {
if (!used[i]) {
used[i] = true;
if (dfs(nums, used, i+1, k, sum+nums[i], target)) return true;
used[i] = false;
}
}
return false;
}
}
```
原文地址:https://segmentfault.com/a/1190000017013991