-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubsets.java
More file actions
50 lines (42 loc) · 1.17 KB
/
Copy pathsubsets.java
File metadata and controls
50 lines (42 loc) · 1.17 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
48
49
50
import java.util.*;
public class subsets {
/* subsets:
* Idea from Jiuzhang
* generating as the DFS in Graph Search
* use DFS as the helper
*/
public static List<List<Integer>> subsets(int[] S) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (S == null) {
return ret;
}
Arrays.sort(S);
dfs(S, 0, new ArrayList<Integer> (), ret);
return ret;
} // close subsets
public static void dfs(int[] S, int index, List<Integer> path, List<List<Integer>> ret) {
ret.add(new ArrayList<Integer>(path));
for(int i = index; i < S.length; i++) {
path.add(S[i]);
dfs(S, i + 1, path, ret);
path.remove(path.size() - 1);
} // close for
} // close dfs
/* subsets1:
* also the idea of DFS
* my own edition
*/
public static void main(String[] args) {
int[] S = {1, 2, 3};
List<List<Integer>> alist = subsets(S);
for (int k = 0; k < alist.size(); k++) {
List<Integer> aElement = alist.get(k);
System.out.print("[");
for (int m = 0; m < aElement.size(); m++) {
int e = aElement.get(m);
System.out.print(e + " ");
} // close m for
System.out.print("], ");
} // close k for
}
}