Problem Statement:

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1: Input: nums = [1,2,2] Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2: Input: nums = [0] Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

Solution:

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        solve(nums, result, new ArrayList<>(), 0);
        return result;
    }
 
    private void solve(int[] nums, List<List<Integer>> list, List<Integer> sublist, int start){
        if(start == nums.length){
            list.add(new ArrayList<>(sublist));
            return;
        }
 
        //pick
        sublist.add(nums[start]);
        solve(nums, list, sublist, start+1);
        sublist.remove(sublist.size()-1);
 
        //if not pick go to the next number
        while(start < nums.length - 1 && nums[start] == nums[start + 1]){
            start++;
        }
        solve(nums, list, sublist, start + 1);
    }
}