Some problems have no formula: the only way to solve them is to try all the possibilities. Generating all the subsets, orderings or combinations of some data is the starting point. Recursion is the perfect tool, because each decision leaves a smaller problem of the same kind.
A problem = a chain of decisions
To generate all the subsets of [1, 2, 3] you have to decide, for each element, whether it goes in or not. Each decision is a fork, and all of them together form a decision tree:
# (nothing decided)
# / # without 1 with 1
# / \ / # without 2 with 2 without 2 with 2
# / \ / \ / \ / # w/o3 w3 w/o3 w3 w/o3 w3 w/o3 w3
#
# 8 leaves = 8 subsets = 2 · 2 · 2
Each leaf of the tree (when all the elements have been decided) is a solution.
Generating all the subsets
def subsets(values, i, current, result):
if i == len(values): # base case: all decided
result.append(list(current)) # we store a COPY
return
subsets(values, i + 1, current, result) # option 1: without the element
current.append(values[i]) # option 2: with the element
subsets(values, i + 1, current, result)
current.pop() # undo
result = []
subsets([1, 2, 3], 0, [], result)
print(result)
# [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
There are three ideas that will repeat throughout the topic:
- Base case: when nothing is left to decide, the solution is recorded.
- A single working list (
current) shared among all the calls: it is modified before going down and undone when coming back (pop()). - Store a copy with
list(current): if you storedcurrentdirectly, by continuing to modify it you would change the solutions already stored.
# The most typical mistake: storing the list, not a copy
big = []
current = [1]
big.append(current)
current.append(2)
print(big) # [[1, 2]] it has changed!
good = []
current = [1]
good.append(list(current))
current.append(2)
print(good) # [[1]]
You practise it in All subsets.
How many solutions there are
With *n* elements there are 2ⁿ subsets: 1 024 with 10 elements, over a million with 20, over a billion with 30. Exhaustive algorithms are correct, but they grow very fast. That is why, in the following articles, you will learn to prune the branches that cannot lead to any solution.
def how_many(n):
return 2 ** n
for n in (5, 10, 20, 30):
print(n, how_many(n))
# 5 32
# 10 1024
# 20 1048576
# 30 1073741824
General template
def solve(state, result):
if is_solution(state):
result.append(copy(state))
return
for option in options(state):
apply(state, option) # choose
solve(state, result) # explore
undo(state, option) # undo
# choose -> explore -> undo
# It is the backtracking outline that we develop in the following articles.