Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
- Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
解法——递归
要注意跳过相同的数字不加入其中避免重复
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
dfs(res, new ArrayList<Integer>(), nums, 0);
return res;
}
private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] nums, int start) {
// TODO Auto-generated method stub
res.add(new ArrayList<Integer>(list));
for(int i=start;i<nums.length;i++)
{
list.add(nums[i]);
dfs(res,list,nums,i+1);
list.remove(list.size()-1);
while (i + 1 < nums.length && nums[i] == nums[i + 1])
++i;
}
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Subsets II.
Memory Usage: 38.4 MB, less than 44.79% of Java online submissions for Subsets II.
解法二——迭代
public List<List<Integer>> subsetsWithDup(int[] nums){
List<List<Integer>> res = new ArrayList<List<Integer>>();
res.add(new ArrayList<Integer>());
if(nums==null||nums.length==0)
return res;
Arrays.sort(nums);
int size=1,last=nums[0];
for(int i=0;i<nums.length;i++){
if(last!=nums[i])
{
size=res.size();
last=nums[i];
}
int newsize=res.size();
for(int j=newsize-size;j<newsize;j++)
{
List<Integer> list=new ArrayList<Integer>(res.get(j));
list.add(nums[i]);
res.add(list);
}
}
return res;
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Subsets II.
Memory Usage: 38.2 MB, less than 47.32% of Java online submissions for Subsets II.