Problem
Given an array of distinct integers nums, return all possible subsets of the array. The solution set must not contain duplicate subsets. The order of the subsets does not matter.Example(s)
Consider the following example(s) to understand the expected input and output.Input
nums = [1,2,3]
Output
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Solution
This solution uses Backtracking to generate all possible subsets. For each element, the recursion has two choices: include the element in the current subset or skip it.
After exploring the choice of including an element, the element is removed from the current subset so that the algorithm can explore the choice of excluding it.
This include-or-skip decision for every element produces all possible subsets.
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, int index,
List<Integer> current, List<List<Integer>> result) {
// The current subset is a valid subset.
result.add(new ArrayList<>(current));
for (int i = index; i < nums.length; i++) {
// Choose the current element.
current.add(nums[i]);
// Continue with the next element.
backtrack(nums, i + 1, current, result);
// Undo the choice.
current.remove(current.size() - 1);
}
}
Complexity
Forn elements, there are 2n possible subsets. Since each subset can contain up to n elements, the time complexity is O(n × 2n).
The recursion depth is at most
O(n), excluding the space required for storing the output.
Comments
No comments yet. Ask a question or share what helped.