2
public List<List<Integer>> subsetsWithDup(int[] nums) {3
// Sort the input array to handle duplicates properly5
// Start the recursion with an empty prefix list6
return subset(new ArrayList<Integer>(), nums);9
// Recursive function to generate subsets10
public List<List<Integer>> subset(ArrayList<Integer> prefix, int[] nums) {11
List<List<Integer>> result = new ArrayList<>();13
// Base case: If there are no elements in nums, add the current prefix to result14
if (nums.length == 0) {15
result.add(new ArrayList<>(prefix));19
// Include the first element of nums in the prefix20
ArrayList<Integer> withCurrent = new ArrayList<>(prefix);21
withCurrent.add(nums[0]);23
// Recursive call with the first element included24
List<List<Integer>> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));26
List<List<Integer>> right = new ArrayList<>();28
// Check for duplicates in the prefix and decide whether to include the first element again29
if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {30
// If the current element is a duplicate, don't include it in the prefix31
// This avoids generating duplicate subsets33
// If the current element is not a duplicate, include it in the prefix34
right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));37
// Combine the subsets with and without the current element