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.
看code吧,不是很会写,时间复杂度这个题所有解法都是指数型的 很高
class Solution {
private int subSum;
private int k;
private boolean[] used;
private int[] nums;
public boolean canPartitionKSubsets(int[] nums, int k) {
int sum = 0;
for(int i = 0; i < nums.length; i++){
sum += nums[i];
}
if(sum % k != 0)
return false;
this.subSum = sum / k;
this.k = k;
this.used = new boolean[nums.length];
this.nums = nums;
int index = 0;
return dfs(0,0, 0);
}
public boolean dfs(int index, int sum,int matched){
if(subSum == sum){
return matched + 1 == k || dfs(0,0,matched+1);
}
else if(sum > subSum){
return false;
}
else {
if(index == nums.length){
return false;
}
boolean flag = false;
if(!used[index]){
used[index] = true;
flag = dfs(index+1,sum+nums[index],matched);
used[index] = false;
}
return flag || dfs(index+1, sum, matched);
}
}
}