-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubsets.java
More file actions
executable file
·47 lines (42 loc) · 1.01 KB
/
subsets.java
File metadata and controls
executable file
·47 lines (42 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
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],
[]
]
*/
import java.util.*;
public class subsets{
public static void main(String[] args) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int[] S = {1,2,3};
Arrays.sort(S);
helper(res,S,0);
System.out.println(res);
}
public static void helper(List<List<Integer>> res, int[] S, int i){
if(i == S.length){
res.add(new ArrayList<Integer>());
return;
}
helper(res,S,i + 1);
int n = res.size();
for(int j = 0; j < n; ++j){
List<Integer> tp = new ArrayList<Integer>(res.get(j));
tp.add(0,S[i]);
res.add(tp);
}
return;
}
}