-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathPartitionToKEqualSumSubsets.java
429 lines (341 loc) · 12.5 KB
/
PartitionToKEqualSumSubsets.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package LeetCodeJava.BackTrack;
// https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
import java.util.*;
/**
* 698. Partition to K Equal Sum Subsets
* Medium
* Topics
* Companies
* Hint
* Given an integer array nums and an integer k, return true if it is 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 is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
* Example 2:
*
* Input: nums = [1,2,3,4], k = 3
* Output: false
*
*
* Constraints:
*
* 1 <= k <= nums.length <= 16
* 1 <= nums[i] <= 104
* The frequency of each element is in the range [1, 4].
*
*/
public class PartitionToKEqualSumSubsets {
// V0
// public boolean canPartitionKSubsets(int[] nums, int k) {
//
// }
// V0-1
// IDEA: HASHMAP + BACKTRACK (fixed by gpt)
public boolean canPartitionKSubsets_0_1(int[] nums, int k) {
// edge
if (nums == null || nums.length == 0 || k <= 0)
return false;
int totalSum = 0;
for (int num : nums)
totalSum += num;
if (totalSum % k != 0)
return false;
int target = totalSum / k;
// Step 1: Count frequencies using HashMap
Map<Integer, Integer> cnt_map = new HashMap<>();
List<Integer> num_list = new ArrayList<>();
for (int num : nums) {
cnt_map.put(num, cnt_map.getOrDefault(num, 0) + 1);
}
// Fill num_list with unique values
num_list.addAll(cnt_map.keySet());
// Step 2: Sort in descending order for optimization
num_list.sort((a, b) -> b - a);
// Step 3: Use an array to track current sum of each subset
int[] buckets = new int[k];
return backtrack(0, num_list, cnt_map, buckets, target);
}
/**
* NOTE !!!
*
* we have 2 helper fumc for this problem
*
* 1. backtrack
* 2. tryPlacing
*
*/
private boolean backtrack(int index, List<Integer> num_list, Map<Integer, Integer> cnt_map, int[] buckets,
int target) {
if (index == num_list.size()) {
// All numbers placed, check all buckets
for (int b : buckets) {
if (b != target)
return false;
}
return true;
}
int num = num_list.get(index);
int count = cnt_map.get(num);
// Try placing `num` (count times) into different buckets
return tryPlacing(num, count, buckets, 0, target, index, num_list, cnt_map);
}
private boolean tryPlacing(int num, int count, int[] buckets, int bucketIndex, int target,
int numIndex, List<Integer> num_list, Map<Integer, Integer> cnt_map) {
if (count == 0) {
// Done placing this number, move to next
return backtrack(numIndex + 1, num_list, cnt_map, buckets, target);
}
/**
* NOTE !!!
*
* we loop over `bucket`,
* -> try every bucket, try to add new element (tryPlacing), validate result
*
* (instead of loop over cnt_map)
*
*/
for (int i = bucketIndex; i < buckets.length; i++) {
if (buckets[i] + num > target)
continue;
buckets[i] += num;
/**
* NOTE !!!!
*
* if below tryPlacing recursive call work, return true directly
*/
if (tryPlacing(num, count - 1, buckets, i, target, numIndex, num_list, cnt_map)){
return true;
}
// undo
buckets[i] -= num;
// Optimization: if placing in an empty bucket didn't work, don't try other empty buckets
if (buckets[i] == 0){
break;
}
}
return false;
}
// V0-2
// IDEA: BACKTRACK (fixed by gpt)
public boolean canPartitionKSubsets_0_2(int[] nums, int k) {
if (nums == null || nums.length == 0 || k <= 0) {
return false;
}
// Sum of all elements in the array
int sum = 0;
for (int num : nums) {
sum += num;
}
// If total sum cannot be divided by k, it's impossible to partition
if (sum % k != 0) {
return false;
}
// Target sum for each subset
int target = sum / k;
// Sort the array in descending order to optimize backtracking
Arrays.sort(nums);
reverse_0_2(nums);
// Create a bucket list to track the current sum of each subset
int[] buckets = new int[k];
// Backtracking to partition the array into k subsets
return backtrack_0_2(nums, 0, buckets, target);
}
private boolean backtrack_0_2(int[] nums, int index, int[] buckets, int target) {
if (index == nums.length) {
// If all numbers are used, check if all buckets have the target sum
for (int bucket : buckets) {
if (bucket != target) {
return false;
}
}
return true;
}
int num = nums[index];
// Try placing the current number in any bucket
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] + num <= target) {
buckets[i] += num; // Choose this bucket
if (backtrack_0_2(nums, index + 1, buckets, target)) {
return true;
}
buckets[i] -= num; // Undo the choice if it leads to a dead-end
}
// Optimization: If the bucket is empty or this number is already placed in a previous bucket, no need to try this bucket again
if (buckets[i] == 0) {
break;
}
}
return false;
}
// Helper method to reverse the array (sorting in descending order)
private void reverse_0_2(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
// V1
// https://www.youtube.com/watch?v=mBk4I0X46oI
// https://github.com/neetcode-gh/leetcode/blob/main/java%2F0698-partition-to-k-equal-sum-subsets.java
int target;
public boolean canPartitionKSubsets_1(int[] nums, int k) {
int sum = 0;
for(int n : nums){
sum += n;
}
if(sum % k != 0)
return false;
target = sum / k;
boolean[] used = new boolean[nums.length];
return backtrack(nums, 0, k, 0, used);
}
private boolean backtrack(int[] nums, int i, int k, int subsetSum, boolean[] used){
if(k == 0)
return true;
if(subsetSum == target)
return backtrack(nums, 0, k-1, 0, used);
for(int j = i; j < nums.length; j++){
if(j > 0 && !used[j-1] && nums[j] == nums[j-1])
continue;
if(used[j] || subsetSum + nums[j] > target)
continue;
used[j] = true;
if(backtrack(nums, j+1, k, subsetSum + nums[j], used))
return true;
used[j] = false;
}
return false;
}
// V2
// https://leetcode.com/problems/partition-to-k-equal-sum-subsets/solutions/1772704/java-solution-with-comments-100-faster-1-3x14/
public boolean canPartitionKSubsets_2(int[] nums, int k) {
int sum = 0;
for (int i : nums) {
sum += i;
}
//sum%k must equal to 0 if not just return false
//if we have to to divide the array greater than array size retun false(we can't)
if (sum % k != 0 || nums.length < k)
return false;
//sort so we can take last element and start filling our bucket
Arrays.sort(nums);
//our target is sum/k and we have to find this in nums, k times then it is valid
return canPartitionKSubsets(nums, sum / k, nums.length - 1, new int[k]);
}
public boolean canPartitionKSubsets(int a[], int target, int i, int bucket[]) {
//we have taken all the elements
if (i == -1)
return true;
//start filling the buckets
for (int j = 0; j < bucket.length; j++) {
//can we take this ith element
if (bucket[j] + a[i] <= target) {
//if we take this element
bucket[j] += a[i];
//go to next element (in our case go to smallest ele bcz we sorted)
//if we can fill all buckets then return true
if (canPartitionKSubsets(a, target, i - 1, bucket))
return true;
//means we can't fill other buckets if we take ith element so leave this element
bucket[j] -= a[i];
}
//if our bucket is empty means we have not taken any elements in the buckets
if (bucket[j] == 0)
break;
}
//all buckets are full but i is pointing to some element (elements still left)
//or our bucket is empty means we haven't take any element (not valid)
return false;
}
// V3-1
// https://leetcode.com/problems/partition-to-k-equal-sum-subsets/solutions/5559337/crazy-best-problem-to-solve-must-solve-t-6ksg/
public boolean canPartitionKSubsets_3_1(int[] nums, int k) {
int sum = Arrays.stream(nums).sum();
if (sum % k != 0)
return false;
int targetSum = sum / k;
Arrays.sort(nums);
// add a reverse it helps!
return backtrack(nums.length - 1, nums, new int[k], targetSum);
}
private boolean backtrack(int index, int[] nums, int[] sums, int targetSum) {
if (index < 0)
return true;
for (int i = 0; i < sums.length; i++) {
if (sums[i] + nums[index] > targetSum)
continue;
sums[i] += nums[index];
if (backtrack(index - 1, nums, sums, targetSum)) {
return true;
}
sums[i] -= nums[index];
if (sums[i] == 0)
break;// why ? explanation given below
}
return false;
}
// V3-2
// https://leetcode.com/problems/partition-to-k-equal-sum-subsets/solutions/5559337/crazy-best-problem-to-solve-must-solve-t-6ksg/
public boolean canPartitionKSubsets_3_2(int[] nums, int k) {
int sum = Arrays.stream(nums).sum();
if (sum % k != 0)
return false;
int targetSum = sum / k;
Arrays.sort(nums);
reverse(nums); // Reverse the array to have larger numbers first
List<List<Integer>> subsets = new ArrayList<>();
for (int i = 0; i < k; i++) {
subsets.add(new ArrayList<>());
}
boolean result = backtrack(0, nums, subsets, new int[k], targetSum);
if (result) {
System.out.println("Valid partition found:");
for (int i = 0; i < subsets.size(); i++) {
System.out.println("Subset " + (i + 1) + ": " + subsets.get(i));
}
} else {
System.out.println("No valid partition found.");
}
return result;
}
private boolean backtrack(int index, int[] nums, List<List<Integer>> subsets, int[] sums, int targetSum) {
if (index == nums.length) {
return true; // All numbers have been used
}
for (int i = 0; i < subsets.size(); i++) {
if (sums[i] + nums[index] > targetSum)
continue;
if (i > 0 && sums[i] == sums[i - 1])
continue;
subsets.get(i).add(nums[index]); // Add to subset
sums[i] += nums[index]; // Update sum
if (backtrack(index + 1, nums, subsets, sums, targetSum)) {
return true;
}
sums[i] -= nums[index]; // Revert sum
subsets.get(i).remove(subsets.get(i).size() - 1); // Remove from subset
if (sums[i] == 0)
break; // Optimization: no need to try empty subsets
}
return false;
}
private void reverse(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}