Subsets

Given a set of distinct integers, return all possible subsets.

  • Elements in a subset must be in _non-descending _order.

  • The solution set must not contain duplicate subsets.

Example

If S =[1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Note

提供3种方法:

  • 简单的递归(取或者不取):递归树的每一层判断当前元素取或者不取

  • 更通用的DFS :就是所谓的Backtracking,找到以某几个元素开头的并回复到之前到状态

  • BFS方法:分层输出

Time O(n*2^n)

Space O(n)

Code

Last updated