698. Partition to K Equal Sum Subsets
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
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
.
---
Intuition
If the sum of all elements in array % k != 0
return false
DFS on all combinations, and keep track of sums
Terminate on last index .. reached here only if all sums are valid
return true
for (i = 0... k)
if (sums[i] + nums[index] <= target)
sums[i] += nums[index]
if (dfs(nums, sums, index + 1, target))
return true
sums[i] -= nums[index]
return false
This tries all combinations
Can optimize
Sort the array descending first
It exits early if any sum > target
---
Time - O(K ^ N)
Space - O(N)
---
Related problems
---
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean canPartitionKSubsets(int[] nums, int k) { | |
if (nums == null || nums.length == 0 || k < 1) { | |
return false; | |
} | |
int sum = 0; | |
for (int num: nums) { | |
sum += num; | |
} | |
if (sum % k != 0) { | |
return false; | |
} | |
// Optimization so invalid sums i.e, sum > target => terminate earlier | |
Arrays.sort(nums); | |
reverse(nums); | |
return dfs(nums, 0, new int[k], sum / k); | |
} | |
private boolean dfs(int[] nums, int index, int[] sums, int target) { | |
if (index == nums.length) { | |
return true; | |
} | |
for (int i = 0; i < sums.length; i++) { | |
if (sums[i] + nums[index] <= target) { | |
sums[i] += nums[index]; | |
if (dfs(nums, index + 1, sums, target)) { | |
return true; | |
} | |
// backtrack | |
sums[i] -= nums[index]; | |
} | |
} | |
return false; | |
} | |
private void reverse(int[] nums) { | |
int i = 0, j = nums.length - 1; | |
while (i < j) { | |
int temp = nums[j]; | |
nums[j] = nums[i]; | |
nums[i] = temp; | |
i++; | |
j--; | |
} | |
} | |
} |