CodeBlanks Logo Icon CodeBlanks

Summary - Backtracking

Practice backtracking with a mini N-queens style task.

Summary - Backtracking

Backtracking searches with trial and error, a state tree and pruning. N-queens, permutations and subset sum are examples.

In this mini task you will solve the subset sum problem; combine all steps.

Backtracking systematically walks the solution space; it is a powerful tool for constrained problems.

Practice Subset sum

Write subset_sum(arr, target). Use backtracking to check if any subset sums to target. Print True with print(subset_sum([3, 34, 4, 12, 5, 2], 9)).

Starter code

solution.py
def subset_sum(arr, target):
    # Subset sum exists

Sample solution

solution.py
def subset_sum(arr, target):
    # Subset sum exists
    def backtrack(i, total):
        if total == target:
            return True
        if i >= len(arr) or total > target:
            return False
        if backtrack(i + 1, total + arr[i]):
            return True
        if backtrack(i + 1, total):
            return True
        return False
    return backtrack(0, 0)
print(subset_sum([3, 34, 4, 12, 5, 2], 9))

Expected output

True

Questions and answers

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

1 Summary - Backtracking: match the terms

Term Meaning
backtrack Return
prune Prune
try Try
undo Undo

2 Undo

Question
path.____()
Answer
path.pop()

Explanation: pop is right.

3 When does backtracking 'undo'?

  • Never
  • Every step
  • Only at the start
  • When deepening fails Correct answer

Explanation: When deepening fails.

All lessons in Intermediate