Sorted backtracking with a skip
Time O(n · 2ⁿ) Space O(n)Same as Subsets, after sorting, with if (i > start && nums[i] == nums[i − 1]) continue;.
import java.util.*;
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> out = new ArrayList<>();
dfs(nums, 0, new ArrayList<>(), out);
return out;
}
private void dfs(int[] nums, int start, List<Integer> path, List<List<Integer>> out) {
out.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) continue;
path.add(nums[i]);
dfs(nums, i + 1, path, out);
path.remove(path.size() - 1);
}
}
}Verdict: Generates each distinct subset exactly once.