Ir al contenido
Ayotl

← Todos los retos

Interview challenge · medium · backtracking, recursion

Subsets and Permutations (Backtracking)

El reto

El enunciado va en inglés, igual que en el vídeo.

Given a list of distinct items, generate (a) every subset, also called the power set, and (b) every permutation, every possible ordering of all the items. Both are classic backtracking problems. Here the items are the letters of "abc", so each subset and each permutation prints as a short word; the same code works for a list of distinct numbers such as [1, 2, 3].

Example

items: a b c

subsets (2^3 = 8):        {}  a  ab  abc  ac  b  bc  c
permutations (3! = 6):    abc  acb  bac  bca  cab  cba

Idea: build a path one item at a time and explore every way to extend it.

- *Subsets:* every path is a subset, so print it as soon as you reach it (the empty path is {}). Then try adding each item that comes *after* the last one you used, so the same subset never appears twice in another order. - *Permutations:* a path is complete only when it holds every item. To extend it, try each item that is not in the path yet.

After exploring a choice, undo it (*un-choose*) and try the next one. In Python the path is a new string on each call, so the undo is free; in C the path is one shared buffer, so it is reset by hand. There are 2ⁿ subsets and n! permutations, so the time grows with the size of the output.

La solución

# Subsets and Permutations - ayotl.dev
def subsets(s, start=0, cur=""):
    # every path from the root is a subset
    print(cur or "{}", end=" ")
    for i in range(start, len(s)):
        # add s[i], then only later items
        subsets(s, i + 1, cur + s[i])


def perms(s, cur=""):
    if len(cur) == len(s):
        print(cur, end=" ")  # a full order
        return
    for ch in s:
        if ch not in cur:  # each item once
            perms(s, cur + ch)


print("subsets:", end=" ")
subsets("abc")
print()
print("permutations:", end=" ")
perms("abc")
print()

$ python3 subsets_permutations.py

subsets: {} a ab abc ac b bc c

permutations: abc acb bac bca cab cba

El vídeo

Ver en YouTube →