This question is part of NeetCode150 series.
Problem Description
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Solution
For each element, we can two choices - either to include that element or exclude it from the current subset.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
helper(nums, new ArrayList<>(), 0);
return ans;
}
public void helper(int[] nums, List<Integer> current, int idx){
if(idx == nums.length){
ans.add(new ArrayList<>(current));
return;
}
//Including
current.add(nums[idx]);
helper(nums, current, idx+1);
//Excluding
current.remove(current.size()-1);
helper(nums, current, idx+1);
}
}