Opening the reading…
Opening the reading…
DYNAMIC PROGRAMMING LEVEL 2 › DP WITH BITMASK
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Every valid partition has the same target for each subset: total sum divided by k. If the division is not exact, the answer is immediately false. Once the target is known, the problem becomes choosing unused numbers that fill one bucket exactly, then repeating that job for the remaining buckets.
The order of the buckets does not matter, and the order of numbers inside a bucket does not matter. Backtracking explores choices while marking numbers as used, then reverses a choice when it cannot lead to a complete partition. Sorting from largest to smallest makes impossible partial buckets fail early, while symmetry rules avoid exploring arrangements that represent the same partition.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(k x n x 2^n) worst case | A search state is determined by which of the n positions are used and which bucket is being filled. Exploring a state may scan up to n positions, and completing up to k buckets can expose that work repeatedly; descending order, duplicate skipping, and the empty-bucket symmetry break reduce the observed search but do not remove the exponential worst case. |
| Space | O(n + k) extra space | The used vector stores one flag per value and the recursion stack has at most n value choices plus bucket transitions, so the working space is linear in n and k. The input array is sorted in place, and there is no returned collection whose storage needs to be counted; the bound is largest for a deeply nested failed search. |
#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
using namespace std;
class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % k != 0) return false;
int target = total / k;
sort(nums.begin(), nums.end(), greater<int>());
if (nums[0] > target) return false;
vector<bool> used(nums.size(), false);
return backtrack(nums, target, k, 0, 0, used);
}
private:
bool backtrack(const vector<int>& nums, int target, int k,
int curSum, int start, vector<bool>& used) {
if (k == 0) return true;
if (curSum == target) {
return backtrack(nums, target, k - 1, 0, 0, used);
}
for (int i = start; i < static_cast<int>(nums.size()); ++i) {
if (used[i]) continue;
if (curSum + nums[i] > target) continue;
used[i] = true;
if (backtrack(nums, target, k, curSum + nums[i], i + 1, used)) {
return true;
}
used[i] = false;
if (curSum == 0) return false;
while (i + 1 < static_cast<int>(nums.size()) &&
nums[i + 1] == nums[i]) {
++i;
}
}
return false;
}
};The transition on curSum == target is the key structural choice. It does not mark another number or continue from the current index; it resets the scan to zero because the next bucket may use any still-unused value. The used vector carries the real partition state across that reset, so a number placed in an earlier bucket can never be reused.
Because n is at most 16, you can represent the used set by an n-bit mask. Define dp[mask] as the sum currently accumulated in the bucket being built after using exactly the positions in mask, with the sum taken modulo target. A remainder of zero means the previous bucket ended exactly and the next one is empty. This is a different arrangement of the same state, not an asymptotic miracle: it stores every reachable used set instead of searching only paths that survive backtracking.
#include <numeric>
#include <vector>
using namespace std;
class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % k != 0) return false;
int target = total / k;
int n = static_cast<int>(nums.size());
int fullMask = 1 << n;
vector<int> dp(fullMask, -1);
dp[0] = 0;
for (int mask = 0; mask < fullMask; ++mask) {
if (dp[mask] == -1) continue;
for (int i = 0; i < n; ++i) {
if (mask & (1 << i)) continue;
if (dp[mask] + nums[i] > target) continue;
int nextMask = mask | (1 << i);
dp[nextMask] = (dp[mask] + nums[i]) % target;
}
}
return dp[fullMask - 1] == 0;
}
};The bitmask version uses O(n x 2^n) time and O(2^n) extra space, excluding the input and required boolean result. It is often easier to reason about when you want memoized states or a predictable state table, while backtracking usually uses much less memory and can be faster because it stops as soon as it finds a partition. With n limited to 16, both are reasonable engineering choices.