Skip to content

Commit 0d09cf3

Browse files
Create 78-Subsets.java
1 parent 884b3b9 commit 0d09cf3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

java/78-Subsets.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//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.
2+
//This video was good for code explanation. https://www.youtube.com/watch?v=6BPurabdAl4&t=508s&ab_channel=Fraz
3+
class Solution {
4+
public List<List<Integer>> subsets(int[] nums) {
5+
List<List<Integer>> ans = new ArrayList<>();
6+
List<Integer> list = new ArrayList<>();
7+
helper(ans, 0, nums, list);
8+
return ans;
9+
}
10+
11+
public void helper(List<List<Integer>> ans, int start, int[] nums, List<Integer> list) {
12+
if (start>=nums.length) {
13+
ans.add(new ArrayList<>(list)); //In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values.
14+
} else {
15+
//add the element and start the recursive call
16+
list.add(nums[start]);
17+
helper(ans, start+1, nums, list);
18+
//remove the element and do the backtracking call.
19+
list.remove(list.size()-1);
20+
helper(ans, start+1, nums, list);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)