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 =
If S =
[1,2,2], a solution is:[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
模板题,重点在于如何去除重复,一开始一直WA,跪在去除重复的方法上了。应该是从排好序的数组前面开始,一个一个的加数,然后后面跳过所有重复的部分,比如2,2,2,那么过程就是{2,2,2};{2,2};{2};{};这样。
public List<List<Integer>> subsetsWithDup(int[] num) {
List<Integer> list = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(num);
subsets(num, 0, list, result);
return result;
}
public void subsets(int[] num, int beg, List<Integer> list, List<List<Integer>> result) {
if(beg == num.length) {
result.add(new ArrayList<Integer>(list));
}
else {
list.add(num[beg]);
subsets(num, beg+1, list, result); // repeat to add duplicate elements
list.remove(list.size() - 1);
while(beg < num.length - 1 && num[beg] == num[beg+1]) beg++; // skip the rest duplicate elements
subsets(num, beg+1, list, result);
}
}
public List<List<Integer>> subsetsWithDup(int[] num) {
List<Integer> list = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(num);
result.add(list);
int cnt = 1, pre = num[0];
for(int i = 0; i < num.length; i++) {
if(num[i] != pre) {
cnt = result.size();
pre = num[i];
}
int beg = result.size() - cnt;
int n = result.size();
for(int j = beg; j < n; j++) {
list = new ArrayList<Integer>(result.get(j));
list.add(num[i]);
result.add(list);
}
}
return result;
}
没有评论:
发表评论