Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Generate Subsets

Recursion & Backtrackingmedium

Implement `subsets(nums)` returning all subsets (the power set). Build them by recursing in index order so subsets appear in the standard backtracking order.

Sample tests

Input: subsets([1,2,3])
Output: [[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
Input: subsets([])
Output: [[]]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A nondeterministic order makes results hard to compare; follow index order.

Learning resources

  • Wikipedia: Backtracking
Approach & explanation (try first)

Backtracking over include/skip choices enumerates all subsets. O(2^n) outputs.

Loading...
⌘/Ctrl + Enter

Run your code to see results.