AceYourInterviews
Checking sign-in…

118. Subsets

IntermediateBacktracking with independent path snapshots

List every selection of input values in which each position is either included or excluded. Within a selected subset, keep the values in their original relative order.

The empty selection is a valid subset. The task asks for all selections, so returning just one subset or only one subset size is insufficient.

Example 1

Input

[1,2]

Output

[[],[1],[1,2],[2]]

Explanation: All four choices appear; another outer order is also valid.

Example 2

Input

[]

Output

[[]]

Explanation: The empty set has one subset, itself.

Constraints

  • 0 <= nums.length <= 16
  • -231 <= nums[i] <= 231 - 1
  • All input values are distinct.
Hints
Hint 1

Describe a subset as an increasing sequence of chosen input indices.

Hint 2

Each recursive state already represents one valid subset.

Hint 3

Copy the path, choose a later index, recurse after it, then undo.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Choose, recurse, undo

[1,2]
[[],[1],[1,2],[2]]