-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAllSubsets.java
More file actions
116 lines (70 loc) · 1.84 KB
/
AllSubsets.java
File metadata and controls
116 lines (70 loc) · 1.84 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
Subset
Problem Description
Given a set of distinct integers, A, return all possible subsets.
NOTE:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Also, the subsets should be sorted in ascending ( lexicographic ) order.
The list is not necessarily sorted.
Problem Constraints
1 <= |A| <= 16
INTMIN <= A[i] <= INTMAX
Input Format
First and only argument of input contains a single integer array A.
Output Format
Return a vector of vectors denoting the answer.
Example Input
Input 1:
A = [1]
Input 2:
A = [1, 2, 3]
Example Output
Output 1:
[
[]
[1]
]
Output 2:
[
[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]
]
Example Explanation
Explanation 1:
You can see that these are all possible subsets.
Explanation 2:
You can see that these are all possible subsets.
*/
/*
Solution Approach
For every element, you have 2 options.
You may either include the element in your subset or you will not include the element in your subset.
Make the call for both the cases.
Remember to include base case to avoid infinite calling.
Can you also do it iteratively?
Hint: You can use the fact that each number from 0 to 2N - 1, represent each subset of N elements.
*/
public class Solution {
ArrayList<ArrayList<Integer>> res;
public ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> A) {
Collections.sort(A);
res = new ArrayList<>();
genSubset(A, 0, new ArrayList<>());
return res;
}
public void genSubset(ArrayList<Integer> list, int start, ArrayList<Integer> ans){
res.add(new ArrayList<>(ans));
for(int i=start;i<list.size();i++){
ans.add(list.get(i));
genSubset(list, i+1, ans);
ans.remove(ans.size()-1);
}
}
}