90. Subsets II

https://leetcode.com/problems/subsets-ii/

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
---
Intuition
---
Related problems
78-subsets
46-permutations
47-permutations-ii
39-combination-sum
40-combination-sum-ii
---
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// Sort to track duplicates
Arrays.sort(nums);
List<Integer> prefix = new ArrayList<Integer>();
ans.add(prefix);
int start = 0, existing = 0;
for (int i = 0; i < nums.length; i++) {
// If current number is duplicate of prev, start from previous start, instead of 0
start = i > 0 && nums[i] == nums[i - 1] ? existing : 0;
// Iterate upto end of ans, add current element to each existing entry
existing = ans.size();
for (int j = start; j < existing; j++) {
prefix = new ArrayList<Integer>(ans.get(j));
prefix.add(nums[i]);
ans.add(prefix);
}
}
return ans;
}
}
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// Sort to track duplicates
Arrays.sort(nums);
List<Integer> prefix = new ArrayList<Integer>();
dfs(nums, 0, prefix, ans);
return ans;
}
private void dfs(int[] nums, int current, List<Integer> prefix, List<List<Integer>> ans) {
ans.add(new ArrayList<Integer>(prefix));
for (int i = current; i < nums.length; i++) {
// Skip duplicates.. i > current to avoid out of bounds
if (i > current && nums[i] == nums[i - 1]) {
continue;
}
prefix.add(nums[i]);
dfs(nums, i + 1, prefix, ans);
prefix.remove(prefix.size() - 1);
}
}
}