Dynamic Programming · Pattern 11 of 12

Bitmask DP: a subset as the state

When n is small (about 20 or less), store "which items are already used" as the bits of an integer. dp[mask] is the best answer for that subset, built from a smaller mask with one item or one group removed.

2 variations · 6 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • n is tiny (n <= 16 or 20) and the order or grouping of items matters
  • Assign items to workers, sessions or teams
  • Cover a small set of required skills or letters

The template

Bitmask DP
// Work Sessions: dp[mask] = {sessions used, time used in the last session}, the smaller the better
int minSessions(int[] tasks, int sessionTime) {
    int n = tasks.length, full = 1 << n;
    int[][] dp = new int[full][];
    dp[0] = new int[]{1, 0};               // one open, empty session
    for (int mask = 1; mask < full; mask++) {
        dp[mask] = new int[]{n + 1, 0};
        for (int i = 0; i < n; i++) {
            if ((mask >> i & 1) == 0) continue;
            int[] p = dp[mask ^ (1 << i)];     // task i is the one done last
            int[] cand = p[1] + tasks[i] <= sessionTime
                ? new int[]{p[0], p[1] + tasks[i]}   // fits in the open session
                : new int[]{p[0] + 1, tasks[i]};     // start a new session
            if (cand[0] < dp[mask][0] || (cand[0] == dp[mask][0] && cand[1] < dp[mask][1])) dp[mask] = cand;
        }
    }
    return dp[full - 1][0];
}

// Minimum Time to Finish All Jobs: the w-th worker takes a submask of what is left
int minimumTimeRequired(int[] jobs, int k) {
    int n = jobs.length, full = 1 << n;
    int[] sum = new int[full];             // sum[mask] = total time of the jobs in mask
    for (int mask = 1; mask < full; mask++)
        sum[mask] = sum[mask & (mask - 1)] + jobs[Integer.numberOfTrailingZeros(mask)];
    int[] dp = sum.clone();                // one worker does everything in mask
    for (int w = 2; w <= k; w++) {
        int[] next = new int[full];
        for (int mask = 0; mask < full; mask++) {
            next[mask] = dp[mask];
            for (int sub = mask; sub > 0; sub = (sub - 1) & mask)   // every submask
                next[mask] = Math.min(next[mask], Math.max(dp[mask ^ sub], sum[sub]));
        }
        dp = next;
    }
    return dp[full - 1];
}

The variations

  1. 1Pack items into bins or workers

    Either add one item at a time (dp[mask] remembers the sessions used and the load of the open one), or give a whole submask to the next worker: dp[w][mask] = min over sub of max(dp[w - 1][mask ^ sub], sum[sub]), which costs O(3ⁿ). Account Balancing counts the most groups whose net debt is zero.

  2. 2Cover a set of requirements

    The mask is the set of skills (or letters) covered so far. Each person ORs their skills into the mask; dp[mask] keeps the smallest team that reaches it. Shortest Supersequences enumerates which letters appear twice and checks that the rest can be ordered.

Mistakes to avoid

  • Operator precedence: mask >> i & 1 is fine, but mask & 1 << i == 0 is not. Add brackets around every bit test.
  • Looping submasks with sub >= 0: (0 - 1) & mask is mask again, so the loop never ends. Stop at sub > 0.
  • Using bitmask DP when n is 40: 2^40 states is far too many. It is only for very small n.
Next: Combinatorics: count with a formula →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.