Backtracking

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

For each item, branch into include and exclude decisions.

Step 1 / 5
Problem shape
Current lesson

Generate Subsets Lab

Backtracking Intermediate

Generate Subsets

Welcome to the Generate Subsets algorithm lab. For each item, branch into include and exclude decisions. Use it when: Use when all possible groups or bitmask states must be explored. The time complexity is O(2^n), and the space complexity is O(n). The pseudocode is: dfs(i) if i == n record current dfs(i + 1) add a[i] dfs(i + 1) remove a[i] As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(2^n)

Space

O(n)

Pseudocode

dfs(i)
  if i == n record current
  dfs(i + 1)
  add a[i]
  dfs(i + 1)
  remove a[i]
Open deeper structure lesson
1.0x