Search choices with choose, explore and undo, and cut dead branches early: combination sums, balanced brackets, word search and partitions.
A branch is cut only when no answer can lie inside it, and each call restores the shared list and marks exactly as it found them.
Use it when you must find every answer that follows a rule, and many partial answers can be rejected early. Signal words: every combination, all valid, place without clashing.
Prune: before you choose, reject a branch by a bound (the total is too large) or by validity (a rule is already broken).
Choose: change the shared list or marks by one choice.
Explore: call the same function for the next decision.
Undo: restore what you changed. Save a copy when you keep an answer.
Cost: the calls that survive the pruning. The worst case is still exponential, but real inputs are often far smaller.
The cost is the number of calls that survive the pruning, times the work to copy one answer. No rule can promise less than the size of the answer. In the worst case the bound cuts nothing, and the search is as large as the full tree.
def bundles(prices, budget):
found = []
walk(sorted(prices), 0, budget, [], found)
return found
def walk(prices, start, remaining, chosen, found):
# [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if remaining == 0:
found.append(list(chosen))
return
for i in range(start, len(prices)):
# [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if prices[i] > remaining:
break
# [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if i > start and prices[i] == prices[i - 1]:
continue
# [4] Choose the price, and explore with the smaller remainder.
chosen.append(prices[i])
walk(prices, i + 1, remaining - prices[i], chosen, found)
# [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop()public int[][] bundles(int[] prices, int budget) {
int[] sorted = prices.clone();
Arrays.sort(sorted);
List<int[]> found = new ArrayList<>();
walk(sorted, 0, budget, new ArrayList<>(), found);
return found.toArray(new int[0][]);
}
private void walk(int[] prices, int start, int remaining, List<Integer> chosen, List<int[]> found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining == 0) {
found.add(chosen.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = start; i < prices.length; i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] == prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.add(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.remove(chosen.size() - 1);
}
}void walk(const vector<int>& prices, int start, int remaining, vector<int>& chosen, vector<vector<int>>& found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining == 0) {
found.push_back(chosen);
return;
}
for (int i = start; i < (int)prices.size(); i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] == prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.push_back(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop_back();
}
}
vector<vector<int>> bundles(vector<int> prices, int budget) {
sort(prices.begin(), prices.end());
vector<vector<int>> found;
vector<int> chosen;
walk(prices, 0, budget, chosen, found);
return found;
}function walk(prices, start, remaining, chosen, found) {
// [1] Base case: nothing left to pay, so the chosen prices are one bundle. Keep a copy.
if (remaining === 0) {
found.push(chosen.slice());
return;
}
for (let i = start; i < prices.length; i++) {
// [2] Prune by bound: prices are sorted, so this price and every later one is too large.
if (prices[i] > remaining) {
break;
}
// [3] Skip a price equal to the one tried before it at this step: it would repeat a bundle.
if (i > start && prices[i] === prices[i - 1]) {
continue;
}
// [4] Choose the price, and explore with the smaller remainder.
chosen.push(prices[i]);
walk(prices, i + 1, remaining - prices[i], chosen, found);
// [5] Undo the choice, so the next price starts from the same bundle.
chosen.pop();
}
}
function bundles(prices, budget) {
const found = [];
walk(prices.slice().sort((a, b) => a - b), 0, budget, [], found);
return found;
}def all_brackets(pairs):
found = []
extend(pairs, 0, 0, [], found)
return found
def extend(pairs, opened, closed, text, found):
# [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if len(text) == 2 * pairs:
found.append("".join(text))
return
# [2] Open a bracket only while some are left to open, then explore and undo.
if opened < pairs:
text.append("(")
extend(pairs, opened + 1, closed, text, found)
text.pop()
# [3] Close a bracket only while one is open, then explore and undo.
if closed < opened:
text.append(")")
extend(pairs, opened, closed + 1, text, found)
text.pop()public String[] allBrackets(int pairs) {
List<String> found = new ArrayList<>();
extend(pairs, 0, 0, new StringBuilder(), found);
return found.toArray(new String[0]);
}
private void extend(int pairs, int opened, int closed, StringBuilder text, List<String> found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if (text.length() == 2 * pairs) {
found.add(text.toString());
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.append('(');
extend(pairs, opened + 1, closed, text, found);
text.deleteCharAt(text.length() - 1);
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.append(')');
extend(pairs, opened, closed + 1, text, found);
text.deleteCharAt(text.length() - 1);
}
}void extend(int pairs, int opened, int closed, string& text, vector<string>& found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if ((int)text.size() == 2 * pairs) {
found.push_back(text);
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.push_back('(');
extend(pairs, opened + 1, closed, text, found);
text.pop_back();
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.push_back(')');
extend(pairs, opened, closed + 1, text, found);
text.pop_back();
}
}
vector<string> allBrackets(int pairs) {
vector<string> found;
string text;
extend(pairs, 0, 0, text, found);
return found;
}function extend(pairs, opened, closed, text, found) {
// [1] Base case: every bracket is placed, so the text is one answer. Keep it as a string.
if (text.length === 2 * pairs) {
found.push(text.join(""));
return;
}
// [2] Open a bracket only while some are left to open, then explore and undo.
if (opened < pairs) {
text.push("(");
extend(pairs, opened + 1, closed, text, found);
text.pop();
}
// [3] Close a bracket only while one is open, then explore and undo.
if (closed < opened) {
text.push(")");
extend(pairs, opened, closed + 1, text, found);
text.pop();
}
}
function allBrackets(pairs) {
const found = [];
extend(pairs, 0, 0, [], found);
return found;
}def count_queens(n):
return place(n, 0, [False] * n, [False] * (2 * n), [False] * (2 * n))
def place(n, row, cols, down, up):
# [1] Base case: every row has a queen, so this placement counts once.
if row == n:
return 1
total = 0
for col in range(n):
# [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if cols[col] or down[row + col] or up[row - col + n - 1]:
continue
# [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = True
# [4] Explore the next row.
total += place(n, row + 1, cols, down, up)
# [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = False
return totalpublic int countQueens(int n) {
return place(n, 0, new boolean[n], new boolean[2 * n], new boolean[2 * n]);
}
private int place(int n, int row, boolean[] cols, boolean[] down, boolean[] up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row == n) {
return 1;
}
int total = 0;
for (int col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}int place(int n, int row, vector<bool>& cols, vector<bool>& down, vector<bool>& up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row == n) {
return 1;
}
int total = 0;
for (int col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}
int countQueens(int n) {
vector<bool> cols(n, false), down(2 * n, false), up(2 * n, false);
return place(n, 0, cols, down, up);
}function place(n, row, cols, down, up) {
// [1] Base case: every row has a queen, so this placement counts once.
if (row === n) {
return 1;
}
let total = 0;
for (let col = 0; col < n; col++) {
// [2] Prune by validity: skip a square whose column or diagonal already has a queen.
if (cols[col] || down[row + col] || up[row - col + n - 1]) {
continue;
}
// [3] Choose the square: mark its column and its two diagonals.
cols[col] = down[row + col] = up[row - col + n - 1] = true;
// [4] Explore the next row.
total += place(n, row + 1, cols, down, up);
// [5] Undo the marks, so the next square starts from the same board.
cols[col] = down[row + col] = up[row - col + n - 1] = false;
}
return total;
}
function countQueens(n) {
return place(n, 0, new Array(n).fill(false), new Array(2 * n).fill(false), new Array(2 * n).fill(false));
}This version stops the loop at the first price above the remainder, but it does not sort the prices first.
This version skips a price equal to the previous one with the test i > 0, and not i > start.
This version of the queens search marks the column and diagonals, but never clears them after the call.
For the prices 1 to 26 and a budget of 175, which is half the total, the search made 33,554,432 calls. The full set of subsets has 67,108,864. The bound cut only half of the tree.
systemdesignmastery.dev/dsa/cheatsheets/backtracking-and-pruning