Skip to content

Commit da5aef3

Browse files
authored
Create Subsets.java
1 parent ec3e1ed commit da5aef3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Backtracking/Subsets.java

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//LeetCode 78. Subsets
2+
//Question - https://leetcode.com/problems/subsets/
3+
4+
class Solution {
5+
public List<List<Integer>> subsets(int[] nums) {
6+
List<List<Integer>> res = new ArrayList<>();
7+
helper(nums, 0, new ArrayList<>(), res);
8+
9+
return res;
10+
}
11+
12+
public void helper(int nums[], int index, List<Integer> subset, List<List<Integer>> res){
13+
res.add(new ArrayList<>(subset));
14+
15+
/*
16+
For each element we have two choices -
17+
1. Include element in current subset
18+
2. Exclude element from current subset
19+
20+
We start from index 0 and it considers all elements in the array ==> this leads to the
21+
deepest branch of the state space tree.
22+
23+
Each level in the state space tree will signify a subset of different length.
24+
25+
Input ==> [1,2,3]
26+
Output ==> [[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
27+
28+
State space tree ==>
29+
level 0 []
30+
level 1 [1] [2] [3]
31+
level 2 [1,2] [1,3] [2,3]
32+
level 3 [1,2,3]
33+
*/
34+
35+
for(int i = index ; i < nums.length ; i++){
36+
//Choice 1. Include the elment
37+
subset.add(nums[i]);
38+
helper(nums, i + 1, subset, res);
39+
//Choice 2. Exclude the element ==> Basically Backtrack after choosing the element
40+
subset.remove(subset.size()-1);
41+
}
42+
43+
}
44+
}

0 commit comments

Comments
 (0)