Problem: 698. 划分为k个相等的子集
题目
给定一个整数数组 nums 和一个正整数 k,找出是否有可能把这个数组分成 k 个非空子集,其总和都相等。
示例 1:
输入: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
输出: True
说明: 有可能将其分成 4 个子集(5),(1,4),(2,3),(2,3)等于总和。
示例 2:
输入: nums = [1,2,3,4], k = 3
输出: false
提示:
1 <= k <= len(nums) <= 16
0 < nums[i] < 10000
每个元素的频率在 [1,4] 范围内
难度
中等
思路
搜索+剪枝
具体思路可参考:https://mp.weixin.qq.com/s/-WOfsB5XQWnlfanwiOJKxg
解题方法
贪心
复杂度
时间复杂度:
添加时间复杂度, 示例: O(n)O(n)O(n)
空间复杂度:
添加空间复杂度, 示例: O(n)O(n)O(n)
Code
Java
class Solution {
static int[] numsBac;
static int kBac, n, t;
public static boolean canPartitionKSubsets(int[] nums, int k) {
numsBac = nums;
kBac = k;
// nums中元素不是k的倍数,则肯定不可以,输出false
int total = 0;
for(int i:nums) {
total += i;
}
if(total % k != 0) return false;
// 将nums排序
Arrays.sort(nums);
n = nums.length;
t = total / k; //每一个集合中元素和需要凑的值为t
return dfs(n-1, 0, 0, new boolean[n]);
}
/**
* 找 剩余未使用元素的最大值所在的集合 (集合内值总和为t)
* @param idx 搜索空间的分割点
* @param curTotal 集合当前元素和
* @param count 已凑成的数量
* @param vis 集合中元素被使用情况(true 已被使用,false 未被使用)
* @return
*/
public static boolean dfs(int idx, int curTotal, int count, boolean[] vis) {
if(count == kBac) return true; //凑够k个集合
if(curTotal == t) return dfs(n-1, 0, count+1, vis); //nums[n]为最大值所在集合已找到,开始找下一个nums[n-1]所在集合
for(int i = idx; i >= 0; i--){
if(vis[i] || curTotal+numsBac[i] > t) continue; //当前元素已被使用,或集合元素和大于目标值k
vis[i] = true;
if(dfs(i-1, curTotal+numsBac[i], count, vis)){
return true; //nums[i]加上后能凑到,凑成功
}
vis[i] = false; // nums[i]加上凑不到,不使用nums[i],用下一个值
if(curTotal == 0) return false;
}
return false;
}
}