MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / FindAllSubsets

Class FindAllSubsets

java/Backtracking/FindAllSubsets.java:4–27  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2import java.util.List;
3
4public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected