~/problems / Backtracking

Basics: choose k of n (choose, explore, un-choose)

easy basics ~10 min

Write combinations(n: int, k: int) -> list[list[int]] that returns every way to pick k different numbers from 1, 2, ..., n, ignoring order. Write each pick as an increasing list. The picks themselves can come back in any order (the tests sort them).

combinations(4, 2)   # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
combinations(3, 3)   # [[1, 2, 3]]
combinations(3, 0)   # [[]]   one way to pick nothing
  • 0 <= n <= 12 and 0 <= k <= n + 2. If k > n there are no picks: return [].
  • Write the recursion yourself; don't use itertools.

Shape of the recursion: backtrack(start, path) tries each number i from start to n. It appends i to path (choose), calls backtrack(i + 1, path) (explore), then pops i (un-choose). When path has k numbers, record it.

Show hint

record a copy (path[:]), because path keeps changing after you record it, and pass i + 1 so no number is picked twice or in a different order.

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc