Partition to K Equal Sum Subsets
Master this topic with zero to advance depth.
Partition to K Equal Sum Subsets
Filling the Buckets
We need to divide numbers into groups, where each group has the same sum. This target sum is TotalSum / K.
Pruning Strategies (Crucial for Hard)
- If
TotalSumis not divisible by , return False immediately. - Sort
numsin descending order to fill buckets with larger numbers first (fails faster on impossible branches). - If a bucket cannot take the current number and it's the first number in the bucket, skip because further search will fail too.
Partition an array into K subsets of equal sum. Includes visual bucket-filling trace.
Examples
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Approach 1
Level I: Backtracking (Optimized with Sorting)
Intuition
Try putting each number into each of the K buckets.
To optimize, we sort descending. In each step, we iterate through K buckets. If bucket[j] + nums[idx] <= target, we add it and recurse. If we hit the end, success.
âą O(K^N)đž O(N)
Detailed Dry Run
nums=[5,4,3,2,1], target=5, k=3
1. Pick 5: Add to B1 (5). OK.
2. Pick 4: Add to B2 (4). OK.
3. Pick 3: B1(8)>5 (â), B2(7)>5 (â), B3(3). OK.
4. Pick 2: B1(5) (â skip), B2(6) (â), B3(5). OK.Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.