-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubset.java
More file actions
60 lines (59 loc) · 1.91 KB
/
subset.java
File metadata and controls
60 lines (59 loc) · 1.91 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
51
52
53
54
55
56
57
58
59
60
public class Solution {
ArrayList<ArrayList<Integer>> r;
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
// Start typing your Java solution below
// DO NOT write main() function
r=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> sofar=new ArrayList<Integer>();
Arrays.sort(S);
s(S,0,sofar);
return r;
}
public void s(int[] S,int ind,ArrayList<Integer> sofar) {
if(ind==S.length) {
ArrayList<Integer> cp=new ArrayList<Integer>(sofar);
r.add(cp);
return;
}
//if(ind>0&&S[ind]==S[ind-1])
//s(S,ind+1,sofar);
//else {
sofar.add(S[ind]);
s(S,ind+1,sofar);
sofar.remove(sofar.size()-1);
s(S,ind+1,sofar);
//}
}
}
public class Solution {
ArrayList<ArrayList<Integer>> r;
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
r=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> sofar=new ArrayList<Integer>();
Arrays.sort(num);
s(num,0,sofar);
return r;
}
public void s(int[] S,int ind,ArrayList<Integer> sofar) {
if(ind==S.length) {
ArrayList<Integer> cp=new ArrayList<Integer>(sofar);
r.add(cp);
return;
}
if(sofar.contains(S[ind])) {
sofar.add(S[ind]);
s(S,ind+1,sofar);
sofar.remove(sofar.size()-1); // still need remove previous one!!!!
// any time change the data structure before a recursive call,
// when it returns back, must need change it back!!
}
else {
sofar.add(S[ind]);
s(S,ind+1,sofar);
sofar.remove(sofar.size()-1);
s(S,ind+1,sofar);
}
}
}