DP on Intervals, Trees & Subsets
When the subproblems are ranges, subtrees or sets.
Prefixes are the default subproblem, but many problems refuse them. The cheapest way to multiply a chain of matrices depends on where a range is split; the best guest list for a company party depends on who reports to whom; the shortest delivery route depends on which stops are already done. Make the subproblem a range, a subtree or a set, and the same recipe works.
What you’ll learn
- Solve interval DPs with over ranges, filled by increasing length: matrix-chain order in , the "last event" trick, and palindrome partitioning.
- Solve tree DPs by combining children in post-order: maximum independent set, minimum vertex cover, subtree sizes and the diameter in , and preview rerooting.
- Solve bitmask DPs over subsets: Held–Karp's for the traveling salesman, assignment in , and submask enumeration in .
- Recognize from a statement and its constraints whether the subproblems are ranges, subtrees or subsets, and avoid each family's classic bugs.
Intervals: split a range, solve both sides
Multiplying a matrix by a matrix takes scalar multiplications. Matrix products are associative, so a chain can be computed as or , with the same result and very different costs. With of size , and :
Trying every parenthesization is hopeless: there are 42 for six matrices and about 1.8 billion for twenty. A prefix of the chain is the wrong subproblem too, since an optimal order may multiply the middle first. The right one is a range of matrices. This is the classic matrix-chain multiplication problem, and the first example of interval DP.
| Range | Candidates (split after …) | Best |
|---|---|---|
| , , | one split each: , , | 1500, 9000, 3000 |
| after : ; after : | 4500 | |
| after : ; after : | 4500 | |
| three candidates: predict them below | ? |
Finish the table: what is the least cost of computing ? Its three candidates split after , after and after .
Show the answer
5000
After : . After : . After : . The best is at 5000; the worst of the five parenthesizations costs 33000.
def matrix_chain(p):
"""Matrix i has shape p[i] x p[i+1]. Least number of scalar multiplications."""
n = len(p) - 1
cost = [[0] * n for _ in range(n)] # cost[i][j]: best for A_i..A_j (inclusive)
for length in range(2, n + 1): # shorter ranges first
for i in range(n - length + 1):
j = i + length - 1
cost[i][j] = min(cost[i][k] + cost[k + 1][j] + p[i] * p[k + 1] * p[j + 1]
for k in range(i, j))
return cost[0][n - 1]
print(matrix_chain([10, 30, 5, 60, 10])) # 5000: (AB)(CD)states, splits each: time in the worst case (exactly split evaluations) and space. Keep the best per cell to print the parenthesization.
Think about the last event
Some interval problems hide their split point. A row of numbers is removed one number at a time; removing earns (its current left neighbor) (its current right neighbor), with an imaginary wall of value 1 at each end. Maximize the total.
Choosing the first removal is a dead end: after it, its two neighbors touch, and the two sides are no longer independent. Choose instead the last number removed strictly between positions and . While the numbers on its two sides are being removed, is still standing, so the left part only ever sees and as boundaries and the right part only and . When finally goes, its neighbors are exactly and .
def best_removal(a):
b = [1] + a + [1] # walls of value 1
n = len(b)
dp = [[0] * n for _ in range(n)] # dp[i][j]: numbers strictly between i and j
for gap in range(2, n): # j - i, shorter gaps first
for i in range(n - gap):
j = i + gap
dp[i][j] = max(dp[i][k] + dp[k][j] + b[i] * b[k] * b[j]
for k in range(i + 1, j)) # k: the LAST one removed
return dp[0][n - 1]
print(best_removal([2, 4, 3])) # 33: remove 4 (24), then 2 (6), then 3 (3)time. A brute force over all removal orders agrees on random inputs.
Why does the recurrence choose the number removed last in a range, rather than the one removed first?
- Removing the last number earns the most, so it decides the optimum
- The last number's neighbors are the range's fixed ends, so the parts on its two sides are independent subproblems
- Both choices give valid recurrences; "last" is merely faster
- So that the table can be filled by increasing length
Show the answer
B. The last number's neighbors are the range's fixed ends, so the parts on its two sides are independent subproblems
Until is removed it separates the two sides, so each side is solved on its own with fixed boundaries, and itself scores . After removing the first number, its neighbors become adjacent and the sides interact, so no recurrence over independent ranges exists.
Interval tables also serve as building blocks. To cut a string into the fewest palindromes, first fill ( is a palindrome iff and ), an interval table, then run a prefix DP over the pairs. For "noonabbad" the answer is 3 pieces, noon | abba | d, so 2 cuts.
Trees: children first
On a rooted tree the natural subproblem is a subtree: the answer for vertex combines the answers of its children, and different children's subtrees share nothing. Any order that handles every child before its parent works, such as a post-order traversal or the reverse of a BFS order, and each edge is used a constant number of times: in all. This is tree DP.
Maximum independent set (the largest set of vertices with no edge inside, say employees invited without their direct boss). Keep two numbers per vertex: , the best in 's subtree with chosen, and , the best with not chosen.
| Vertex (finishing order) | D | H | I | E | B | F | J | G | C | A |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 3 | 1 | 1 | 1 | 2 | 6 | |
| 0 | 0 | 0 | 2 | 3 | 0 | 0 | 1 | 2 | 5 |
from collections import defaultdict
def max_independent_set(n, edges, root=0):
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent, order = [-1] * n, [root]
for v in order: # BFS: the list grows while we scan it
for c in adj[v]:
if c != parent[v]:
parent[c] = v
order.append(c)
take, skip = [1] * n, [0] * n # unit weights: take[v] counts v itself
for v in reversed(order): # children before parents
p = parent[v]
if p >= 0:
take[p] += skip[v]
skip[p] += max(take[v], skip[v])
return max(take[root], skip[root])No recursion, so a path of vertices cannot overflow Python's call stack. time and space.
The same pattern computes many other things in one pass: subtree sizes (); the minimum vertex cover, which is the complement of a maximum independent set (here vertices, such as ); and the diameter, the longest path, which passes through some highest vertex and uses its two deepest child subtrees (here 6 edges, H–E–B–A–C–G–J).
Rerooting answers a question for every choice of root without separate passes. For the sum of distances from to all vertices, move the root from a vertex to its child : the vertices in 's subtree get one step closer, the other one step farther, so . One pass computes the sizes and , a second pass pushes the answers down: for all roots.
Think first On the tree above (), the distances from B to all vertices sum to 19, and E's subtree has 3 vertices. What is the sum of the distances from E to all vertices?
- : E, H and I come one step closer () and the other seven vertices move one step farther (). Counted directly: E is at distance 0; B, H, I at 1; A, D at 2; C at 3; F, G at 4; J at 5.
Subsets: bitmasks when n is about 20
In the traveling salesman problem a salesman starts at city 0, visits each of the other cities once and returns, along the shortest tour. Brute force tries tours. But the best way to continue a partial route depends only on which cities it has visited and where it stands, not on the order of the visits. A set of cities fits in the bits of one integer, a bitmask, so the states are pairs (set, last city): bitmask DP.
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
// dp[S][j]: shortest path from city 0 through exactly the cities of S, ending at j.
// Cities 1..n-1 are stored as bits 0..n-2 of S.
long long held_karp(const vector<vector<long long>>& d) {
int n = d.size(), m = n - 1;
const long long INF = 1LL << 60;
vector<vector<long long>> dp(1 << m, vector<long long>(m, INF));
for (int j = 0; j < m; j++) dp[1 << j][j] = d[0][j + 1];
for (int S = 1; S < (1 << m); S++) // increasing S: every set after its subsets
for (int j = 0; j < m; j++) {
if (!(S >> j & 1) || dp[S][j] == INF) continue;
for (int k = 0; k < m; k++) // extend the path to an unvisited city k
if (!(S >> k & 1)) {
int T = S | 1 << k;
dp[T][k] = min(dp[T][k], dp[S][j] + d[j + 1][k + 1]);
}
}
long long best = INF;
for (int j = 0; j < m; j++) best = min(best, dp[(1 << m) - 1][j] + d[j + 1][0]);
return best;
}
int main() {
vector<vector<long long>> d = {{0, 3, 4, 2, 7}, {3, 0, 4, 6, 3}, {4, 4, 0, 5, 8},
{2, 6, 5, 0, 6}, {7, 3, 8, 6, 0}};
printf("%lld\n", held_karp(d)); // 19
}Adding a city to makes the integer larger, so increasing integer order handles every set after all of its subsets: a topological order for free. With there are entries and about extensions, fine in C++; brute force would need about tours.
Bitmask DPs often need only the set. To give workers jobs at least total cost, let be the least cost of having workers do the jobs in , where is the number of set bits (popcount): worker is always the next one to place, so no "last element" is needed, and the DP costs .
def assign(cost):
"""cost[i][j]: worker i does job j. Least total cost, each job done once. O(2^n * n)."""
n = len(cost)
best = [float('inf')] * (1 << n) # best[mask]: workers 0..k-1 did the jobs in mask, k = popcount
best[0] = 0
for mask in range(1 << n): # increasing order: every mask after its submasks
i = bin(mask).count('1') # the next worker to place
if i == n:
continue
for j in range(n):
if not mask >> j & 1:
new = mask | 1 << j
best[new] = min(best[new], best[mask] + cost[i][j])
return best[(1 << n) - 1]
cost = [[2, 3, 4, 4], [1, 7, 7, 8], [1, 6, 9, 8], [2, 6, 1, 3]]
print(assign(cost)) # 12: jobs 3, 0, 1, 2; giving each worker the cheapest free job costs 18For large the Hungarian algorithm solves assignment in . The bitmask DP shines when the cost of a job depends on which jobs came before, which the Hungarian algorithm cannot express.
Some transitions combine a set with any of its subsets, such as "close one more group, made of some of the remaining items". Enumerating the submasks of every mask (sub = (sub - 1) & mask) costs
because each element is either outside the mask, inside the submask, or inside the mask but not the submask. is fast; is not.
Think first A DP loops over every mask of items and, for each mask, over all of its submasks. About how many (mask, submask) pairs does it visit?
: each item is outside the mask, in the submask, or in the mask only. That is far fewer than the pairs of arbitrary masks, but far more than the steps of a DP that adds one item at a time.
Recognizing it
The subproblems' shape is usually visible in the statement and the constraints:
- Ranges: "merge adjacent", "parenthesize", "remove from a row and score by the current neighbors", "cut a string into pieces", with up to about 500 (for ) or 5000 (for ). The state is , and the transition picks a split point or the last event inside the range.
- Subtrees: a hierarchy, "each employee has one manager", "a network with no cycles", a tree with up to –. A few numbers per vertex, combined from the children, in .
- Subsets: "visit every city", "assign each worker", "which items are already used", with at most about 20. The state is a mask, often with a last element: or .
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Cheapest order to multiply a chain of matrices, or to merge adjacent piles when a merge costs the total size | over a split point | |
| Remove numbers from a row; each removal scores with its current neighbors | The last one removed between and | |
| Invite the most employees, never an employee together with their direct manager | per vertex | |
| Shortest closed route through cities | Held–Karp | |
| Fewest work sessions of length for tasks | = (sessions, time used in the last one), minimized in that order |
tasks with durations up to 10 hours must be scheduled into work sessions of at most 10 hours; a task cannot be split. You want the fewest sessions. Which approach fits?
- Interval DP over the tasks in input order
- Greedy: sort the tasks by duration and fill each session in turn
- Bitmask DP over the set of tasks done, keeping (sessions, hours used in the last session)
- A knapsack table over the 10 hours of one session
Show the answer
C. Bitmask DP over the set of tasks done, keeping (sessions, hours used in the last session)
Tasks may go in any order, so the state is the set of tasks already scheduled: masks times 16 tasks to add, about steps. It is bin packing, which is strongly NP-hard in general but easy for .
Key takeaways
- Interval DP: over ranges, combining two shorter ranges at a split point (or around the last event), filled by increasing length; matrix-chain order costs .
- Tree DP: a few numbers per vertex, combined from the children in post-order; maximum independent set uses and runs in .
- Bitmask DP: the state is a subset, often with a last element; Held–Karp solves the traveling salesman in for up to about 20.
- The constraints point to the structure: and "merge adjacent" for intervals, a hierarchy with up to or more for trees, and with "which items are used" for bitmasks.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the matrix-chain table, reads and for . Which filling order is valid?
- Row by row: , and increasing within a row
- By increasing length
- Column by column, decreasing
- Any order, since each cell is computed only once
Show the answer
B. By increasing length
Both cells read have strictly shorter ranges, so filling by increasing length guarantees they are ready. (Rows with decreasing and increasing also work.)
In the tree DP for maximum independent set, which formula is right for , the best value in 's subtree with not chosen?
Show the answer
C.
If is not chosen, each child may be chosen or not, independently of the others, so each child contributes the better of its two values.
Held–Karp runs on cities, with city 0 fixed as the start. Roughly how many table entries are there, and how much work in total?
- About entries, one per tour
- About entries and steps
- About entries and 8000 steps
- About entries and steps
Show the answer
B. About entries and steps
ranges over the subsets of the other 19 cities and over 19 cities; each entry is extended to at most 19 new cities, about steps. That is the point of the DP: tours collapse into states.
In a tree with vertices, is the sum of the distances from to all vertices, and is a child of whose subtree has vertices. Which formula moves the answer from to ?
Show the answer
A.
The vertices of 's subtree get one step closer and the other one step farther: . Two passes, one for the sizes and and one to push answers down, give every vertex's answer in .
An array of numbers must be cut into contiguous pieces, from left to right; a piece costs (its maximum) (its length) plus a fixed fee. Minimize the total. Which DP fits?
- Interval DP over a split point,
- A prefix DP , with a running maximum
- Bitmask DP over the set of cut positions
- Tree DP over a Cartesian tree of the array
Show the answer
B. A prefix DP , with a running maximum
A piece's cost depends only on the piece, and the pieces are taken left to right, so the state is just "where the last piece ends". For each , scanning downward keeps the running maximum of the last piece: steps.
Go deeper
- Interval DP · Matrix-chain multiplication, optimal BSTs and polygon triangulation.
- Tree DP & Rerooting · Independent sets on trees, and answers for every root in O(n).
- Bitmask DP & the Held–Karp Algorithm · DP over subsets in O(2ⁿ n²), and broken-profile DP.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §14.2, "Matrix-chain multiplication".
- A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 10 (dynamic programming over subsets) and chapter 14 (tree algorithms) (free online).
- J. Erickson, Algorithms (2019), chapter 3, "Dynamic Programming" (free online).
- R. Bellman, "Dynamic programming treatment of the travelling salesman problem," Journal of the ACM 9(1) (1962), 61–63.