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], [] ]比Subsets要求稍高的一点是这里会出现duplicate elements。想法是如果下一个元素是duplicate,那么在下一次循环中就不是遍历之前所有的solution set,而是只遍历前一次循环中新增加的Solution sets。以[1,2,2]为例:
start: []
itr1: [] [1]
itr2:[] [1] [2] [1,2]
如果itr3按照之前的做法对每个set都加入新的元素2,那么会产生重复:
[] [1] [2] [1,2] [2] [1,2] [1,2,2] [2,2]
可以看到只有[1,2,2]和[2,2]是我们需要新加入的solution set。
因此itr3只应该循环前一次循环新增加的部分
代码如下:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(num == null || num.length == 0)
return res;
Arrays.sort(num);
res.add(new ArrayList<Integer>());
int start = 0;
for(int i = 0; i < num.length; i++){
int size = res.size();
for(int j = start; j < size; j++){
List<Integer> sol = new ArrayList<Integer>(res.get(j));
sol.add(num[i]);
res.add(sol);
}
if(i < num.length - 1 && num[i] == num[i + 1])
start = size;
else
start = 0;
}
return res;
}
}