题目:
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2] 输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
思路:好长时间之后再来做题。。。还是先参考了网上大神的做法。原文链接:https://blog.csdn.net/xygy8860/article/details/47053633
以下的代码由一些深度优先搜索的感觉,整体使用了递归的思路。
代码:
public class Solution {
List<List<Integer>> list;//结果集
List<Integer> al;//每一项
public List<List<Integer>> subsetsWithDup(int[] nums) {
list = new ArrayList<List<Integer>>();
al = new ArrayList<Integer>();
Arrays.sort(nums);
//排列组合
count(nums,al,0);
return list;
}
private void count(int[] nums,List<Integer> al,int j){
list.add(new ArrayList<Integer>(al));//不重复的才添加
for(int i = j; i < nums.length;i++){
if(i == j || nums[i] != nums[i-1]){//去除重复
al.add(nums[i]);//添加
count(nums,al,i+1);
al.remove(al.size()-1);//去除,为下一个结果做准备
}
}
}
}
执行最快的代码:
思路:有点看不懂
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
res.add(new ArrayList<>());
int last = nums[0], size = 1;
for (int j = 0; j < nums.length; j++) {
// 遍历,把目前所拥有的所有子集都作为新子集,并在每个新子集中添加新元素
if (last != nums[j]) {
last = nums[j];
size = res.size();
}
int tempSize = res.size();
for (int i = tempSize- size; i < tempSize; i++) {
res.add(new ArrayList<>(res.get(i)));
res.get(res.size() - 1).add(nums[j]);
}
}
return res;
}