78_Subsets

[Medium][Backtracking]

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]

Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Solution:

Idea:

  • There are 2n2^n subsets in total. Because each integer can be included or not.

  • For each integer, use recursion to get subsets for the two possibilities:

    1. the subset includes the integer

    2. the subset doesn't include the integer

  • For storing each solution, there are two ways:

    1. initialize a list called sol, update the elements when we progress.

    2. In the helper function, set a parameter called selected__so__far, which includes all the selected integers. Update this parameter when we progress.

Time Complexity: O(n2n)O(n 2^n) there are 2n2^n paths in the tree

Space Complexity: O(n2n)O(n 2^n) for the output

Code 1: use a list to update current solution

Code 2: use a parameter in the helper function to store current solution

Solution 2: Mit Manipulation

Last updated