Code

Backtracking

Backtracking explores every possible choice, one step at a time, and undoes a choice when it leads nowhere. It follows a simple recipe: choose, explore, un-choose.

def permutations(items):
    results, path = [], []

    def explore():
        if len(path) == len(items):      # a full answer
            results.append(path.copy())
            return
        for item in items:
            if item not in path:
                path.append(item)        # choose
                explore()                # explore
                path.pop()               # un-choose

    explore()
    return results

print(permutations([1, 2, 3]))  # 6 orderings

Backtracking gets much faster when you prune: stop exploring a branch as soon as you know it can't work.

Assignment

The guild airship can carry exactly target kilos. Write subset_sums(weights, target) that returns every combination of crates whose weights add up to exactly target.

  1. weights is a list of positive whole numbers. Use each crate at most once.
  2. Each combination is a list, with crates in the same order as in weights.
  3. subset_sums([2, 3, 5, 7], 10) gives [[2, 3, 5], [3, 7]] (any order).
  4. Return [] if nothing works.