题目
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], [] ]实现
publicArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>>res = new ArrayList<>();
if(num == null || num.length == 0) {
returnres;
}
Arrays.sort(num);
ArrayList<Integer>list = new ArrayList<>();
solve(num,0, res, list);
returnres;
}
privatevoid solve(int[] num, int start, ArrayList<ArrayList<Integer>> res,ArrayList<Integer> list) {
res.add(newArrayList<>(list));
if(start >= num.length)
return;
for(int i = start; i < num.length; i++) {
if(i > start && num[i] == num[i - 1]) {
continue;
}
list.add(num[i]);
solve(num,i + 1, res, list);
list.remove(list.size()- 1);
}
}
本文介绍了一种解决含重复元素集合的所有可能子集问题的算法。该算法首先对输入数组进行排序,然后通过递归方式生成所有不重复的子集,并确保每个子集内的元素按非递减顺序排列。
1万+

被折叠的 条评论
为什么被折叠?



