Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]这道题出现了重复的元素,需要加入一步重复的判断,即只要出现了重复,我们就只从后半部分开始添加,前半部分跳过。
比如[][1]这个时候又出现了1要添加,如果全部添加就是[][1][1][1,1]就出现了重复,如果只是后半部分的话,就是[][1][1,1]
所以只需要在重复的时候添加上start=size就可以了
代码参考Code_Ganker
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
result.add(new ArrayList<Integer>());
if (num == null || num.length == 0)
return result;
Arrays.sort(num);
int start = 0;
for (int i = 0; i < num.length; i++) {
int size = result.size();
for (int j = start; j < size; j++) {
ArrayList<Integer> temp = new ArrayList<Integer>(result.get(j));
temp.add(num[i]);
result.add(temp);
}
if (i < num.length - 1 && num[i] == num[i + 1])
start = size;
else
start = 0;
}
return result;
}