Backtracking

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

Choose each unused value for the next position.

Step 1 / 5
Problem shape
Current lesson

Generate Permutations Lab

Backtracking Intermediate

Generate Permutations

Welcome to the Generate Permutations algorithm lab. Choose each unused value for the next position. Use it when: Use when order matters and every arrangement must be considered. The time complexity is O(n!), and the space complexity is O(n). The pseudocode is: dfs(path) if path length == n record path for each unused value mark used dfs(path + value) unmark used As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n!)

Space

O(n)

Pseudocode

dfs(path)
  if path length == n record path
  for each unused value
    mark used
    dfs(path + value)
    unmark used
Open deeper structure lesson
1.0x