Backtracking Basics
How a program can build every answer one choice at a time, undo each choice, and drop branches that cannot work.
Picture three coins on a table, worth 2, 3 and 5. Which handfuls of them pay exactly 5? By hand, you would pick up a coin, add another, and put the last one back when the total goes over 5. Then you would try a different coin in its place.
Backtracking is that habit written as a program. It builds an answer one choice at a time and undoes each choice once everything after it has been tried. It suits problems that ask for every selection, order or placement that follows some rules.
A tree of choices
Start with an easier question: which handfuls can you make at all from the coins [2, 3, 5]
Look at the box [ ][2][2, 3]
Why is there no "add 2" line under [3][3, 2][2, 3][2][2, 3, 5]
The orange numbers give the order in which a search visits the boxes. It goes as deep as it can first: [ ][2][2, 3][2, 3, 5][2, 3, 5][2][2, 5]
That step back is where the name comes from. Taking out the last coins to return to an earlier box, then trying the next choice from there, is called backtracking. Going down one branch to the bottom before starting the next one is called depth-first order.
Choose, explore, un-choose
How does a program walk that tree when it does not know how many coins it will get? Nested loops would need one loop per coin. The answer is a method that handles a single box and then calls itself for every box hanging below it. Here it is, named collect
static void collect(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
result.add(new ArrayList<>(hand)); // save a copy of this box
for (int i = start; i < coins.length; i++) {
hand.add(coins[i]); // choose
collect(coins, i + 1, hand, result); // explore
hand.remove(hand.size() - 1); // un-choose
}
}
The parameter starthandhandresult
- Choose:
puts the coin in the hand, which moves down one line in the picture.hand.add(coins[i]) - Explore:
visits every box below. Passingcollect(coins, i + 1, hand, result) as the newi + 1 lets only coins to the right follow.start - Un-choose:
takes the coin back out, so the next coin in the loop starts from the same hand.hand.remove(hand.size() - 1)
The un-choose line is the dashed back-up arrow in the picture. Without it, the coins from one branch would still be in the hand when the next branch starts.
Cutting branches early
Now back to the first question: which handfuls pay exactly 5? The slow way is to let collect
A better search keeps a running total and gives up on a branch as soon as it cannot work. In this picture each box shows its sum:
The box [2][2, 5][3, 5][2, 3][2, 3, 5]
Dropping a branch early because it cannot lead to an answer is called pruning. The method payleftleftleft
for (int i = start; i < coins.length; i++) {
if (coins[i] > left) {
break; // sorted: every later coin is too big too
}
hand.add(coins[i]);
pay(coins, i + 1, left - coins[i], hand, result);
hand.remove(hand.size() - 1);
}
The loop can breakpayExactly
With three coins the saving is small: the pruned search makes 5 calls, one per solid box, against 8 for the slow way. With more coins the gap is huge. For coins worth 1 to 20 and a target of 10, both ways find the same 10 handfuls. The slow way makes 1,048,576 calls, and the pruned search makes 43.
When order matters
What if the question changes to "in how many orders can the three coins be laid in a row?" Now [2, 3][3, 2]
The method laybooleanusedrow
for (int i = 0; i < coins.length; i++) {
if (used[i]) {
continue; // this coin is already in the row
}
used[i] = true;
row.add(coins[i]);
lay(coins, used, row, result);
row.remove(row.size() - 1);
used[i] = false;
}
Here a row is saved only when it holds all three coins, at the bottom of the tree. The tree of rows has 1 box at the top, 3 below it, 6 on the next level and 6 at the bottom. So lay
Equal values in the input
Swap the 5 for a second 3, so the coins are [2, 3, 3]collect[2, 3][3]
Two choices that leave the same box are called siblings. In the picture, "add 2", "add first 3" and "add second 3" are siblings under [ ][2]
The two orange lines are different. Under [3][3, 3][2, 3, 3]
In code that takes two parts. The coins are sorted, so equal values sit side by side. Then the loop skips a coin that has the same value as the coin before it, but only when that coin was a sibling, which means i > start
for (int i = start; i < coins.length; i++) {
if (i > start && coins[i] == coins[i - 1]) {
continue; // same value as the sibling just tried
}
hand.add(coins[i]);
collectNoRepeats(coins, i + 1, hand, result);
hand.remove(hand.size() - 1);
}
The box [3]starti > start
The complete program
The class below holds the four searches: subsetscollectpayExactlypayorderslaysubsetsNoRepeatscollectNoRepeatscallscollectpaylaypayBySearchingAll
Its main[2, 3, 5][2, 3, 3]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Backtracking {
static int calls; // how many times a backtracking method was entered
// Every handful of coins: each box of the tree is saved.
static List<List<Integer>> subsets(int[] coins) {
List<List<Integer>> result = new ArrayList<>();
calls = 0;
collect(coins, 0, new ArrayList<>(), result);
return result;
}
static void collect(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
calls++;
result.add(new ArrayList<>(hand)); // save a copy of this box
for (int i = start; i < coins.length; i++) {
hand.add(coins[i]); // choose
collect(coins, i + 1, hand, result); // explore
hand.remove(hand.size() - 1); // un-choose
}
}
// Every handful that adds up to exactly target, cutting branches that go over it.
static List<List<Integer>> payExactly(int[] coins, int target) {
int[] sorted = coins.clone();
Arrays.sort(sorted);
List<List<Integer>> result = new ArrayList<>();
calls = 0;
pay(sorted, 0, target, new ArrayList<>(), result);
return result;
}
static void pay(int[] coins, int start, int left, List<Integer> hand,
List<List<Integer>> result) {
calls++;
if (left == 0) { // the hand pays exactly the target
result.add(new ArrayList<>(hand));
return;
}
for (int i = start; i < coins.length; i++) {
if (coins[i] > left) {
break; // sorted: every later coin is too big too
}
hand.add(coins[i]);
pay(coins, i + 1, left - coins[i], hand, result);
hand.remove(hand.size() - 1);
}
}
// The slow way: list every handful first, then keep the ones that add up to target.
static List<List<Integer>> payBySearchingAll(int[] coins, int target) {
List<List<Integer>> result = new ArrayList<>();
for (List<Integer> hand : subsets(coins)) {
int sum = 0;
for (int c : hand) {
sum += c;
}
if (sum == target) {
result.add(hand);
}
}
return result;
}
// Every order of laying all the coins in a row.
static List<List<Integer>> orders(int[] coins) {
List<List<Integer>> result = new ArrayList<>();
calls = 0;
lay(coins, new boolean[coins.length], new ArrayList<>(), result);
return result;
}
static void lay(int[] coins, boolean[] used, List<Integer> row, List<List<Integer>> result) {
calls++;
if (row.size() == coins.length) {
result.add(new ArrayList<>(row));
return;
}
for (int i = 0; i < coins.length; i++) {
if (used[i]) {
continue; // this coin is already in the row
}
used[i] = true;
row.add(coins[i]);
lay(coins, used, row, result);
row.remove(row.size() - 1);
used[i] = false;
}
}
// Every handful once, even when two coins have the same value.
static List<List<Integer>> subsetsNoRepeats(int[] coins) {
int[] sorted = coins.clone();
Arrays.sort(sorted);
List<List<Integer>> result = new ArrayList<>();
collectNoRepeats(sorted, 0, new ArrayList<>(), result);
return result;
}
static void collectNoRepeats(int[] coins, int start, List<Integer> hand,
List<List<Integer>> result) {
result.add(new ArrayList<>(hand));
for (int i = start; i < coins.length; i++) {
if (i > start && coins[i] == coins[i - 1]) {
continue; // same value as the sibling just tried
}
hand.add(coins[i]);
collectNoRepeats(coins, i + 1, hand, result);
hand.remove(hand.size() - 1);
}
}
public static void main(String[] args) {
int[] coins = {2, 3, 5};
System.out.println("subsets " + subsets(coins) + ", calls " + calls);
System.out.println("subsets of [] " + subsets(new int[] {}));
System.out.println("pay 5 " + payExactly(coins, 5) + ", calls " + calls);
System.out.println("pay 5, slow way " + payBySearchingAll(coins, 5) + ", calls " + calls);
System.out.println("pay 7 from [5, 3, 2] " + payExactly(new int[] {5, 3, 2}, 7));
System.out.println("pay 1 " + payExactly(coins, 1) + ", calls " + calls);
System.out.println("orders " + orders(coins) + ", calls " + calls);
int[] twoThrees = {2, 3, 3};
System.out.println("plain subsets of [2, 3, 3] " + subsets(twoThrees));
System.out.println("no repeats " + subsetsNoRepeats(twoThrees));
int[] oneToTwenty = new int[20];
for (int i = 0; i < 20; i++) {
oneToTwenty[i] = i + 1;
}
int found = payBySearchingAll(oneToTwenty, 10).size();
System.out.println("1..20, pay 10, slow way: " + found + " handfuls, calls " + calls);
found = payExactly(oneToTwenty, 10).size();
System.out.println("1..20, pay 10, pruned: " + found + " handfuls, calls " + calls);
}
}
Running it prints:
subsets [[], [2], [2, 3], [2, 3, 5], [2, 5], [3], [3, 5], [5]], calls 8
subsets of [] [[]]
pay 5 [[2, 3], [5]], calls 5
pay 5, slow way [[2, 3], [5]], calls 8
pay 7 from [5, 3, 2] [[2, 5]]
pay 1 [], calls 1
orders [[2, 3, 5], [2, 5, 3], [3, 2, 5], [3, 5, 2], [5, 2, 3], [5, 3, 2]], calls 16
plain subsets of [2, 3, 3] [[], [2], [2, 3], [2, 3, 3], [2, 3], [3], [3, 3], [3]]
no repeats [[], [2], [2, 3], [2, 3, 3], [3], [3, 3]]
1..20, pay 10, slow way: 10 handfuls, calls 1048576
1..20, pay 10, pruned: 10 handfuls, calls 43
The first line lists the eight handfuls in the order of the orange numbers in the first picture, from [][5][[]][]
The line pay 5 [[2, 3], [5]], calls 5[5, 3, 2]pay 7[[2, 5]]payExactlypay 1
The orders[2, 3, 3][2, 3][3]no repeats
The last two lines are the 1 to 20 comparison: the same 10 handfuls, from 1,048,576 calls the slow way and 43 calls with pruning.
Typical traps
What goes wrong when one line of the template is off? Each of the following mistakes compiles, runs and gives a wrong answer without any error message:
- Saving
itself withhand instead of a copy made withresult.add(hand) .new ArrayList<>(hand) - Leaving out the un-choose line,
.hand.remove(hand.size() - 1) - Writing the sibling check as
instead ofi > 0 .i > start - Using the right sibling check on coins that were never sorted.
This program has one method per mistake, each run on the coins used so far:
import java.util.ArrayList;
import java.util.List;
public class BacktrackingTraps {
// Trap 1: saves the shared list itself instead of a copy.
static void noCopy(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
result.add(hand);
for (int i = start; i < coins.length; i++) {
hand.add(coins[i]);
noCopy(coins, i + 1, hand, result);
hand.remove(hand.size() - 1);
}
}
// Trap 2: never takes the coin back out.
static void noUnchoose(int[] coins, int start, List<Integer> hand,
List<List<Integer>> result) {
result.add(new ArrayList<>(hand));
for (int i = start; i < coins.length; i++) {
hand.add(coins[i]);
noUnchoose(coins, i + 1, hand, result);
}
}
// Trap 3: compares with the previous coin even when it is not a sibling (i > 0).
static void skipTooMuch(int[] coins, int start, List<Integer> hand,
List<List<Integer>> result) {
result.add(new ArrayList<>(hand));
for (int i = start; i < coins.length; i++) {
if (i > 0 && coins[i] == coins[i - 1]) {
continue;
}
hand.add(coins[i]);
skipTooMuch(coins, i + 1, hand, result);
hand.remove(hand.size() - 1);
}
}
// Trap 4: the right skip check, but on input that was not sorted.
static void unsortedSkip(int[] coins, int start, List<Integer> hand,
List<List<Integer>> result) {
result.add(new ArrayList<>(hand));
for (int i = start; i < coins.length; i++) {
if (i > start && coins[i] == coins[i - 1]) {
continue;
}
hand.add(coins[i]);
unsortedSkip(coins, i + 1, hand, result);
hand.remove(hand.size() - 1);
}
}
public static void main(String[] args) {
List<List<Integer>> result = new ArrayList<>();
noCopy(new int[] {2, 3, 5}, 0, new ArrayList<>(), result);
System.out.println("no copy: " + result);
result = new ArrayList<>();
noUnchoose(new int[] {2, 3, 5}, 0, new ArrayList<>(), result);
System.out.println("no un-choose: 5th saved " + result.get(4)
+ ", last saved " + result.get(result.size() - 1));
result = new ArrayList<>();
skipTooMuch(new int[] {2, 3, 3}, 0, new ArrayList<>(), result);
System.out.println("i > 0: " + result);
result = new ArrayList<>();
unsortedSkip(new int[] {3, 2, 3}, 0, new ArrayList<>(), result);
System.out.println("not sorted: " + result);
}
}
Running it prints:
no copy: [[], [], [], [], [], [], [], []]
no un-choose: 5th saved [2, 3, 5, 5], last saved [2, 3, 5, 5, 3, 5, 5]
i > 0: [[], [2], [2, 3], [3]]
not sorted: [[], [3], [3, 2], [3, 2, 3], [3, 3], [2], [2, 3], [3]]
The no copyhand
In the no un-choose[2, 5][2, 3, 5, 5][2, 3, 5, 5, 3, 5, 5]
The i > 0[3, 3][2, 3, 3]not sorted[3, 2, 3][3][3, 2][2, 3]
Spotting a backtracking problem
When is backtracking the right tool? Look for a problem that asks for every way, or for one way, to build something from a series of choices under rules. Typical wording is "list all subsets", "every arrangement", or "place the pieces so that no two clash". The inputs are usually small, because the number of answers grows very fast.
Adapting the template to such a problem means answering four questions. Here are the answers for the three searches on the coins:
| Question | Every handful | Pay exactly 5 | Every order |
|---|---|---|---|
| What has been built so far? | the coins in the hand | the coins in the hand and the amount left | the coins in the row, and which are used |
| What can come next? | any coin to the right of the last one | any coin to the right that is not over the amount left | any coin not used yet |
| When is a branch dropped? | never | when the next coin is over the amount left | never; used coins are skipped |
| When is an answer saved? | at every box | when the amount left is 0 | when the row holds every coin |
How much work it is
The cost of a backtracking search is the number of boxes it visits times the work done in each box. For n coins:
- Every handful: O(n · 2n) time, because each coin doubles the number of boxes, which gives 2n of them, and saving a box copies up to n coins.
- Every order: O(n · n!) time, because the bottom level holds n! rows and the levels above hold fewer than 2 · n! boxes together, each running a loop over n coins.
- Pay exactly a target: O(n · 2n) time in the worst case, because pruning only removes boxes from the full tree. How many it removes depends on the coins and the target, as the drop from 1,048,576 calls to 43 shows.
- Space: O(n) besides the answers, because the hand, the row and the chain of open calls never go deeper than n coins.
When a problem asks only how many handfuls pay an amount, not for the handfuls themselves, the same amount left comes up in many branches. Remembering the answer for each amount left, instead of searching it again, is the idea behind
Where to go next
Picking a selection, where order does not matter:
Subsets lists every subset of distinct numbers, the same way lists every handful.collectSubsets II adds equal values and the sibling check.Combination Sum pays a target when each number may be used again and again.Combination Sum II pays a target with each number used once, with pruning and equal values together.
Building an order:
Permutations lists every order with a array, asused does.layPermutations II lists every different order when values repeat.
Placing things under rules:
N-Queens places queens row by row and drops a square as soon as another queen attacks it.Sudoku Solver fills one cell at a time and undoes digits that lead nowhere.Word Search walks a path through a letter grid, marking cells and unmarking them on the way back.