~/problems / Backtracking

Permutations

easy ~15 min

Write permutations(nums) that returns every ordering of nums as a list of lists.

  • The values are distinct integers; 1 <= len(nums) <= 7 (so up to 5,040 results).
  • The permutations can come in any order, but each must appear exactly once.
  • Don't use itertools.permutations; build them yourself.
permutations([4, 9])      # [[4, 9], [9, 4]]  in some order
permutations([1, 2, 3])   # 6 lists: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]
Show hint

build an ordering one position at a time, remembering which indices are already used; after exploring a choice, undo it before trying the next.

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

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