I have a List of elements (1, 2, 3), and I need to get the superset (powerset) of that list (without repeating elements). So basically I need to create a List of Lists that
In the given solution we iterate over every index and include current and all further elements.
class Solution {
public List> subsets(int[] nums) {
List> ans = new ArrayList<>();
if(nums == null || nums.length ==0){
return ans;
}
Arrays.sort(nums);
List subset = new ArrayList<>();
allSubset(nums, ans , subset , 0);
return ans;
}
private void allSubset(int[] nums,List> ans ,List subset , int idx){
ans.add(new ArrayList<>(subset));
for(int i = idx; i < nums.length; i++){
subset.add(nums[i]);
allSubset(nums, ans , subset , i+1);
subset.remove(subset.size() - 1);
}
}
}