-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathSubsets.java
More file actions
36 lines (33 loc) · 987 Bytes
/
Subsets.java
File metadata and controls
36 lines (33 loc) · 987 Bytes
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
/*
* Approach:
- The idea is to use 0/1 recursion to explore all subsets of the array
- Once we have reached the end, add it to the result
-TC: O(2^n * n)-> n for copying the path to the resultant array * choose/not choose for n elements so 2^n
- SC: O(n) -> recursion stack space
*/
class Solution {
List<List<Integer>> res;
public List<List<Integer>> subsets(int[] nums) {
this.res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(nums, path, 0);
return res;
}
private void helper(int[] nums, List<Integer> path, int idx){
//base
if(idx == nums.length){
res.add(new ArrayList<>(path));
return;
}
//logic
//not choose
helper(nums, path, idx + 1);
//choose
//action
path.add(nums[idx]);
//recurse
helper(nums, path, idx + 1);
//backtrack
path.remove(path.size() - 1);
}
}