codejump
MediumPro challengePythonJavaScriptTypeScript

Backtracking — All Subsets

AlgorithmsBacktrackingRecursionArrays

nums holds distinct integers. Return every subset (the power set),
the empty subset included.

This is the template every other backtracking problem reuses: at each step,
choose a number, explore everything that follows from that choice, then
un-choose it and try the next one. Passing a start index forward means a
number is only ever followed by numbers after it, so no subset is built twice.

Output order (deterministic)

  • Each subset is in ascending order.
  • Subsets are listed in lexicographic order. That is the order a

depth-first search produces on the sorted input: [], [1], [1, 2],
[1, 2, 3], [1, 3], [2]...

Examples

solve([1, 2, 3])  → [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
solve([0])        → [[], [0]]

Constraints

  • 0 <= nums.length <= 10, values distinct, in any order.

Sample tests

Test #1The classic example
Input: [[1,2,3]]
Output: [[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
Test #2A single number
Input: [[0]]
Output: [[],[0]]
Test #3The empty set has one subset
Input: [[]]
Output: [[]]