题目:Subsets II
难度:medium
问题描述:
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
解题思路:使用回溯法,难点在于回溯时对重复元素的跳过。迭代2,2,2时,只要对第一个进行迭代即可。跳过重复部分。
具体代码如下:
public class m_90_Subsetsll {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res=new ArrayList<List<Integer>>();
diedai(0,nums,res,new ArrayList<Integer>());
return res;
}
public void diedai(int index,int[]nums,List<List<Integer>> res,List<Integer> list){
if(index==nums.length){
List<Integer> temp=new ArrayList<Integer>(list);
res.add(temp);
return;
}
for(int i=index;i<=nums.length;i++){
if(i==nums.length){
List<Integer> temp=new ArrayList<Integer>(list);
res.add(temp);
return;
}
if(i>index&&nums[i]==nums[i-1]){
continue;
}else{
list.add(nums[i]);
diedai(i+1,nums,res,list);
list.remove(list.size()-1);
}
}
}
public static void main(String[]args){
int[]nums={1,2,2};
m_90_Subsetsll s=new m_90_Subsetsll();
s.subsetsWithDup(nums);
}
}