Search and backtracking · 2 / 15 Theory

Permutations and combinations

Two of the most famous combinatorial problems are ordering elements (permutations) and choosing a group of them (combinations). The difference is whether order matters.

Does order matter?Example with A, B, CCount
PermutationsyesABC, ACB, BAC, BCA, CAB, CBAn!
Combinations (of 2)noAB, AC, BCn! / (k! · (n−k)!)

Permutations

To form a permutation, in each position you can put any letter that has not been used yet. You need to know which ones are used: a list of booleans.

def permutations(letters, current, used, result):
    if len(current) == len(letters):
        result.append("".join(current))
        return
    for i in range(len(letters)):
        if not used[i]:
            used[i] = True                   # choose
            current.append(letters[i])
            permutations(letters, current, used, result)   # explore
            current.pop()                    # undo
            used[i] = False

result = []
permutations("abc", [], [False] * 3, result)
print(result)   # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Notice the loop: there are no longer two options as in the subsets, but as many as free letters. This produces the "choose → explore → undo" pattern inside a for. You practise it with Permutations of a word.

The number of permutations is n!: 24 with 4 letters, 120 with 5, 3 628 800 with 10. It grows even faster than 2ⁿ.

def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

print(factorial(4), factorial(5), factorial(10))   # 24 120 3628800

Combinations

In a combination, {1, 3} and {3, 1} are the same. To avoid generating duplicates an order is imposed: each chosen element must be greater than the previous one. It is enough to pass to the next call the point from which choosing can continue.

def combinations(n, k, start, current, result):
    if len(current) == k:
        result.append(list(current))
        return
    for v in range(start, n + 1):
        current.append(v)
        combinations(n, k, v + 1, current, result)   # the next one, from v + 1
        current.pop()

result = []
combinations(4, 2, 1, [], result)
print(result)   # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

It is the outline of Combinations. Notice the key difference with permutations: here the list of used elements is not needed, because by always moving forward no element can be repeated.

And the standard library?

The itertools module already includes permutations and combinations. You will see them in the standard library lesson; it is worth having programmed the algorithms by hand at least once, because the same structure is used in many problems that itertools does not solve (such as placing queens or solving a sudoku).

import itertools

print(list(itertools.combinations([1, 2, 3, 4], 2)))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
print(list(itertools.permutations("abc"))[:2])
# [('a', 'b', 'c'), ('a', 'c', 'b')]

When to use each pattern

I need...Pattern
To decide "yes or no" for each elementSubsets: two branches per level
All possible ordersPermutations: list of used elements
To choose *k* out of *n* regardless of orderCombinations: start parameter