CodeBlanks Logo Icon CodeBlanks

What is backtracking?

Trial-and-error search method.

What is backtracking?

Backtracking searches by trial and error. At an infeasible step it returns and tries another path.

It walks the solution space like a tree; pruning speeds it up and cuts unnecessary branches.

Backtracking is often used for N-queens, sudoku and maze solving; thanks to its flexibility.

Trial and error

Backtracking takes a step, checks if it can proceed. If yes it deepens; if no it returns.

This is implemented naturally with recursion; each call is a step.

Thanks to recursion, backtracking happens automatically; the call stack holds the state.

Practice Generate subsets

Write subsets(arr). Generate all subsets of an array with backtracking. Print [[], [1], [2], [1, 2]] with print(subsets([1, 2])).

Starter code

solution.py
def subsets(arr):
    # Generate subsets

Sample solution

solution.py
def subsets(arr):
    # Generate subsets
    result = []
    def backtrack(start, path):
        result.append(list(path))
        for i in range(start, len(arr)):
            path.append(arr[i])
            backtrack(i + 1, path)
            path.pop()
    backtrack(0, [])
    return result
print(subsets([1, 2]))

Expected output

[[], [1], [2], [1, 2]]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does backtracking return?

  • Every step
  • When a step is infeasible Correct answer
  • Never
  • Only at the start

Explanation: When a step is infeasible.

2 Recursion base

Question
if len(path) == ____:
Answer
if len(path) == n:

Explanation: n is right.

3 What is backtracking: match the terms

Term Meaning
backtrack Return
try Try
undo Undo
prune Prune

All lessons in Intermediate