首页 > 代码库 > 90. Subsets II

90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 

public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list = new ArrayList<Integer>();
        if (nums.length == 0) {
            result.add(list);
            return result;
        }
        Arrays.sort(nums);
        helper(result, list, nums, 0);
        return result;
        
    }
    private void helper (List<List<Integer>> result, List<Integer> list, int[] nums, int pos) {
       /* if (result.contains(list)) {
            return;
        }*/
       result.add(new ArrayList(list));
       for (int i = pos; i < nums.length; i++) {
           if (i != pos && nums[i] == nums[i - 1]) {
               continue;
           }
           list.add(nums[i]);
           helper(result, list, nums, i + 1);
           list.remove(list.size() - 1);
       }
    }

  

90. Subsets II