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],
  []
]

 这道题就是Subsets的延伸,只不过数组中有重复的数字。

 

 所以每次遇到重复的数字,continue就好。(注意flag的设立,必须有flag,否则结果中会出现一个重复的数字都没有)。

public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    int[] num;
    int len;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        len = nums.length;
        num = nums;
        Arrays.sort(num);
        res.add(new ArrayList<>());
        sub(0,new ArrayList<>() );
        return res;
    }

    public void sub(int start,List<Integer> ans){
        int flag = 0;
        for( int i = start;i<len;i++){
            if( i > 0 && flag == 1 && num[i] == num[i-1])
                continue;
            ans.add(num[i]);
            flag = 1;
            res.add(new ArrayList<Integer>(ans));
            sub(i+1,ans);
            ans.remove(ans.size()-1);
        }
        return ;
    }
}