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 point in the first group must choose at least one connection, and every point in the second group must be chosen at least once. The first requirement is easy to enforce by processing left points one at a time and making each processed point add one edge. The difficult part is remembering which right points have already been covered, because that determines what remains necessary.
There are only size2 right points, so one bit per right point stores exactly this information. After processing some left points, mask bit j is 1 when right point j already has a connection. For the next left point, choose any right point j and set its bit. This allows a left point to have several connections: the same processing stage can add more bits without moving to another left point.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(m n 2^n) | There are m processing stages and 2^n masks. Each stage examines n possible edge choices in the required-edge pass and n possible missing bits in the completion pass, so every state is examined only a constant number of times per right point. |
| Space | O(m 2^n) extra | The table stores m + 1 rows of 2^n states; minCost and the input are smaller-order working data. The returned cost is a scalar, so output storage adds nothing. There is no different input shape that worsens this bound; the largest permitted dimensions simply give the worst case m 2^n states. |
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int connectTwoGroups(vector<vector<int>>& cost) {
int m = cost.size();
int n = cost[0].size();
int fullMask = (1 << n) - 1;
vector<int> minCost(n, INT_MAX);
for (int j = 0; j < n; ++j) {
for (int i = 0; i < m; ++i) {
minCost[j] = min(minCost[j], cost[i][j]);
}
}
const int INF = INT_MAX / 2;
vector<vector<int>> dp(m + 1, vector<int>(1 << n, INF));
dp[0][0] = 0;
for (int i = 1; i <= m; ++i) {
for (int mask = 0; mask <= fullMask; ++mask) {
for (int j = 0; j < n; ++j) {
int newMask = mask | (1 << j);
dp[i][newMask] = min(
dp[i][newMask],
dp[i - 1][mask] + cost[i - 1][j]
);
}
}
for (int mask = fullMask; mask >= 0; --mask) {
for (int j = 0; j < n; ++j) {
if ((mask & (1 << j)) == 0) {
dp[i][mask] = min(
dp[i][mask],
dp[i][mask | (1 << j)] + minCost[j]
);
}
}
}
}
return dp[m][fullMask];
}
};The completion pass is the key placement in the code. Its source state has one more covered bit than its destination state, so descending mask order makes that source available even when it was itself produced by an earlier completion update. The use of minCost[j] is also deliberate: the missing right point does not need to connect to the left point currently being processed.
Only the previous processing row is needed to create the next one, so the two-dimensional table is not necessary. A rolling vector reduces extra space from O(m 2^n) to O(2^n), while preserving the same O(m n 2^n) time. This is a genuine space optimisation rather than a different algorithm; it costs a little more care because the completion pass must update the current row in dependency order.
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int connectTwoGroups(vector<vector<int>>& cost) {
int m = cost.size();
int n = cost[0].size();
int fullMask = (1 << n) - 1;
const int INF = INT_MAX / 2;
vector<int> minCost(n, INT_MAX);
for (int j = 0; j < n; ++j) {
for (int i = 0; i < m; ++i) {
minCost[j] = min(minCost[j], cost[i][j]);
}
}
vector<int> previous(1 << n, INF);
previous[0] = 0;
for (int i = 0; i < m; ++i) {
vector<int> current(1 << n, INF);
for (int mask = 0; mask <= fullMask; ++mask) {
for (int j = 0; j < n; ++j) {
int newMask = mask | (1 << j);
current[newMask] = min(
current[newMask],
previous[mask] + cost[i][j]
);
}
}
for (int mask = fullMask; mask >= 0; --mask) {
for (int j = 0; j < n; ++j) {
if ((mask & (1 << j)) == 0) {
current[mask] = min(
current[mask],
current[mask | (1 << j)] + minCost[j]
);
}
}
}
previous.swap(current);
}
return previous[fullMask];
}
};The rolling version creates current only from previous, then closes current using supersets within current. Descending masks are essential here: mask | (1 << j) is numerically larger than mask, so its completed value has already been settled. After the swap, the old row is discarded. Choose this version when memory matters; choose the table version when inspecting every processing stage makes debugging easier.