Skip to content

Commit f841e20

Browse files
Sean PrashadSean Prashad
Sean Prashad
authored and
Sean Prashad
committed
Add 698_Partition_to_K_Equal_Sum_Subsets.java
1 parent aae1a63 commit f841e20

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public boolean canPartitionKSubsets(int[] nums, int k) {
3+
if (nums == null || nums.length == 0) {
4+
return false;
5+
}
6+
7+
int totalSum = 0;
8+
for (int num : nums) {
9+
totalSum += num;
10+
}
11+
if (totalSum % k != 0) {
12+
return false;
13+
}
14+
15+
int target = totalSum / k;
16+
return helper(nums, k, 0, 0, target, new boolean[nums.length]);
17+
}
18+
19+
private boolean helper(int[] nums, int k, int start, int currSum, int target, boolean[] used) {
20+
if (k == 1) {
21+
return true;
22+
}
23+
if (currSum == target) {
24+
return helper(nums, k - 1, 0, 0, target, used);
25+
}
26+
27+
for (int i = start; i < nums.length; i++) {
28+
if (used[i]) {
29+
continue;
30+
}
31+
used[i] = true;
32+
if (helper(nums, k, i + 1, currSum + nums[i], target, used)) {
33+
return true;
34+
}
35+
used[i] = false;
36+
}
37+
38+
return false;
39+
}
40+
}

0 commit comments

Comments
 (0)