← Practice
πŸ“– BacktrackingLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 4/5Β·~22 min

Backtracking: all subsets

The power set of a list is the collection of all its subsets β€” including the empty set and the full set. A list of k distinct elements has 2 ** k subsets.

Backtracking explores choices one element at a time: for each element you either include it or skip it, recursing on the rest. When you run out of elements, the choices you've made so far form one subset.

In plain steps (you write the Python):

text
build(i, current):
    if i has passed the last index:
        record `current` as one finished subset, then stop
    branch 1: build(i + 1, current)           # skip element i
    branch 2: build(i + 1, current + element i)  # include element i

Your task

Write subsets(nums) where nums is a list of distinct integers. Return a list of all subsets. To keep the output deterministic so it can be checked:

  1. each subset must be a list in ascending order, and
  2. the returned list of subsets must be sorted(...) (Python's default list ordering).
python
subsets([1, 2])     # [[], [1], [1, 2], [2]]
subsets([])         # [[]]
subsets([1, 2, 3])  # [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

Hint: recurse with the include-or-skip choice to generate every subset. Sort each subset so its own elements are ascending, gather them into one list, and sort that whole list before returning it.

Tests

  • two elements
  • empty list
  • three elements
  • single element

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.