Skip to content

Commit ac3691b

Browse files
committed
add: FindAllSubsets
1 parent bc1c0f7 commit ac3691b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

java/Backtracking/FindAllSubsets.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class FindAllSubsets {
5+
public List<List<Integer>> findAllSubsets(int[] nums) {
6+
List<List<Integer>> res = new ArrayList<>();
7+
backtrack(0, new ArrayList<>(), nums, res);
8+
return res;
9+
}
10+
11+
private void backtrack(int i, List<Integer> currSubset, int[] nums, List<List<Integer>> res) {
12+
// Base case: if all elements have been considered, add the
13+
// current subset to the output.
14+
if (i == nums.length) {
15+
res.add(new ArrayList<>(currSubset));
16+
return;
17+
}
18+
// Include the current element and recursively explore all paths
19+
// that branch from this subset.
20+
currSubset.add(nums[i]);
21+
backtrack(i + 1, currSubset, nums, res);
22+
// Exclude the current element and recursively explore all paths
23+
// that branch from this subset.
24+
currSubset.remove(currSubset.size() - 1);
25+
backtrack(i + 1, currSubset, nums, res);
26+
}
27+
}

0 commit comments

Comments
 (0)