-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0078-subsets.java
30 lines (28 loc) · 946 Bytes
/
0078-subsets.java
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
// The idea is to have two conditions:
// One in which we will take the element into consideration,
// Second in which we won't take the element into consideration.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
helper(ans, 0, nums, list);
return ans;
}
public void helper(
List<List<Integer>> ans,
int start,
int[] nums,
List<Integer> list
) {
if (start >= nums.length) {
ans.add(new ArrayList<>(list));
} else {
// add the element and start the recursive call
list.add(nums[start]);
helper(ans, start + 1, nums, list);
// remove the element and do the backtracking call.
list.remove(list.size() - 1);
helper(ans, start + 1, nums, list);
}
}
}