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

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

 

For example,

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

[

  [3],

  [1],

  [2],

  [1,2,3],

  [1,3],

  [2,3],

  [1,2],

  []

]

SOLUTION 1:

使用九章算法的模板:

递归解决。

1. 先对数组进行排序。

2. 在set中依次取一个数字出来即可,因为我们保持升序,所以不需要取当前Index之前的数字。

TIME: 227 ms

 1 public class Solution {
 2     public List<List<Integer>> subsets(int[] S) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (S == null) {
 5             return ret;
 6         }
 7         
 8         Arrays.sort(S);
 9         
10         dfs(S, 0, new ArrayList<Integer> (), ret);
11         
12         return ret;
13     }
14     
15     public void dfs(int[] S, int index, List<Integer> path, List<List<Integer>> ret) {
16         ret.add(new ArrayList<Integer>(path));
17         
18         for (int i = index; i < S.length; i++) {
19             path.add(S[i]);
20             dfs(S, i + 1, path, ret);
21             path.remove(path.size() - 1);
22         }
23     }
24 }
View Code

相关文章:

  • 2021-12-28
  • 2021-10-30
  • 2021-08-14
  • 2022-02-26
  • 2022-02-27
  • 2022-12-23
  • 2021-08-05
  • 2021-06-27
猜你喜欢
  • 2021-10-15
  • 2021-08-09
  • 2021-12-01
  • 2021-07-17
  • 2021-05-26
  • 2021-11-29
  • 2021-09-02
相关资源
相似解决方案