Find Subsets or Power set
Solution to return all possible subsets (the power set) problem.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
int twoPowN = 1 << n;
List<List<Integer>> r = new ArrayList<>();
for (int i=0;i<twoPowN;i++) {
List<Integer> sr = new ArrayList<>();
for(int j=0;j<n;j++) {
int bits = 1 << j;
if ((i & bits) > 0)
sr.add(nums[j]);
}
r.add(sr);
}
return r;
}
}
The approach used is explained in this geeksforgeeks link.
Alternate approach using Recursion
This approach is a direct port of the python code provided in the leetcode discussion.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<Integer>();
dfs(nums, 0, path, ans);
return ans;
}
private void dfs(int[] nums, int ndx, List<Integer> path, List<List<Integer>> ans) {
ans.add(path);
for(int i=ndx;i<nums.length;i++){
List<Integer> npath = new ArrayList<Integer>(path);
npath.add(nums[i]);
ndx = ndx + 1;
dfs(nums, ndx, npath, ans);
}
}
}