Description

Given a list of numbers that may has duplicate numbers, return all possible subsets

Notice

Each element in a subset must be in

  • non-descending order.
  • The ordering between two subsets is free.
  • The solution set must not contain duplicate subsets.
Example

If S =[1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
Solution
public class Solution {
    /*
     * @param nums: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        // write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nums == null) {
            return result;
        }

        Arrays.sort(nums);
        List<Integer> list = new ArrayList<Integer>();
        subsetsWithDup(nums, result, list, 0);
        return result;
    }

    public void subsetsWithDup(int[] nums, List<List<Integer>> result, List<Integer> list, int index) {
        if (index > nums.length) {
            return;
        }

        result.add(new ArrayList<Integer>(list));
        for (int i = index; i < nums.length; i++) {
            if (i > index && nums[i] == nums[i - 1]) {
                continue;
            }

            list.add(nums[i]);
            subsetsWithDup(nums, result, list, i + 1);
            list.remove(list.size() - 1);
        }
    }
}

results matching ""

    No results matching ""