~/problems / Backtracking

Subsets

easy ~15 min

Write subsets(nums) that returns every subset of nums as a list of lists.

  • The values in nums are distinct integers; 0 <= len(nums) <= 10.
  • Include the empty subset and the whole list. No subset may appear twice.
  • The subsets can come in any order, and the elements inside each subset can be in any order.
subsets([5, 2])   # [[], [5], [2], [5, 2]]  in some order
subsets([])       # [[]]
Show hint

each element is either in a subset or not, so there are 2^n subsets. Decide for one index at a time, and undo the choice when you come back.

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

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