CodeBlanks Logo Icon CodeBlanks

State tree

Branch solutions into a tree and walk it.

State tree

Backtracking walks solutions as a tree. Each node is a partial solution, each branch a choice.

Leaves are full solutions; internal nodes are intermediate states and pruning happens here.

The state tree visualizes the solution space; branches are cut early via pruning.

Permutation example

All permutations of an array are built by picking an unused element at each level of the state tree.

For n elements there are n! leaves; each gives a different ordering.

Generating permutations is one of the best known applications of backtracking.

Practice Generate permutations

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

Starter code

solution.py
def perms(arr):
    # Generate permutations

Sample solution

solution.py
def perms(arr):
    # Generate permutations
    result = []
    def backtrack(path, used):
        if len(path) == len(arr):
            result.append(list(path))
            return
        for i in range(len(arr)):
            if not used[i]:
                used[i] = True
                path.append(arr[i])
                backtrack(path, used)
                path.pop()
                used[i] = False
    backtrack([], [False] * len(arr))
    return result
print(perms([1, 2]))

Expected output

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

Questions and answers

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

1 Add choice

Question
path.____(arr[i])
Answer
path.append(arr[i])

Explanation: append is right.

2 State tree: match the terms

Term Meaning
tree Tree
node Partial solution
leaf Full solution
branch Choice

3 What does a leaf represent in the state tree?

  • Full solution Correct answer
  • Partial solution
  • Start
  • Pruning

Explanation: Full solution.

All lessons in Intermediate