78. Subsets

problem description

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],
  []
]

algorithm thought

类似上一题得到组合,只不过这里需要得到所有大小的组合。只需要改变回溯法中,将中间结果push到res的位置,在进入下一个函数的时候就push,而不是在递归基的时候,这样就能到达遍历的效果。

code

algorithm analysis

时间复杂度是O(2^n),对于每一个数,都能选择是放入或者不放入最后数组

Last updated