CodingNodes / Backtracking / Subsets System design Space play · ←→ step · R restart

Problem

You are given an array nums of different integers. Return every subset you can make by picking any of the numbers (none of them, some of them, or all of them).

The list must not contain the same subset twice. The subsets may be returned in any order.

Constraints

  • 1 ≤ nums.length ≤ 10
  • -10 ≤ nums[i] ≤ 10
  • All numbers in nums are different

Examples: pick one to animate

Solutions

TimeO(n · 2ⁿ) SpaceO(n)

Time: There are 2ⁿ subsets and every one is copied into the answer, which costs up to n each.

Space: Besides the output, the recursion is at most n + 1 calls deep and the path holds at most n numbers.

Keep a path. On every call the path is already a valid subset, so save a copy. Then try each number from start onward: add it, recurse with the next position so numbers are only picked left to right (no repeats), and remove it again.