Skip to content
advanced

Subsets by choose, explore, unchoose

Complete the backtracking skeleton that enumerates every subset — the push, the recursive descent, and the undo.

/**
 * Returns every subset of `nums`, each exactly once. `nums` has distinct
 * values and at most ~15 elements.
 */
export function subsets(nums: number[]): number[][] {
  const results: number[][] = []
  const path: number[] = []

  function backtrack(start: number): void {
    // The path as it stands is one complete subset.
    results.push([...path])

    for (let i = start; i < nums.length; i++) {
      path.____(nums[i] as number)
      backtrack(i + 1)
      path.___()
    }
  }

  _________(0)
  return results
}
0/3 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code