78. Subsets

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

解法

使用库函数。

每次遍历都把之前的结果加上新的元素再与之前的结果相加。例如 [1, 2, 3]

第 1 轮:[[]] -> [[], [1]] 第 2 轮:[[], [1]] -> [[], [1], [2], [1, 2]] 第 3 轮:[[], [1], [2], [1, 2]] -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

递归(回溯)

参考

回溯算法

Last updated

Was this helpful?