题目:
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], [] ]
题意及分析:和subsets类似,都是使用回溯的方法求解,不过需要跳过重复的,在剩余的数组中如果当前数字等于前面数字跳过即可。
代码:
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result=new ArrayList<>();
List<Integer> list=new ArrayList<>();
Arrays.sort(nums);
backtracking(result, nums, list, 0);
return result;
}
public void backtracking(List<List<Integer>> result,int nums[],List<Integer> list,int start) {
result.add(new ArrayList<>(list));
for(int i=start;i<nums.length;i++){
if(i>start&&nums[i]==nums[i-1]) continue; //跳过重复的
list.add(nums[i]);
backtracking(result, nums, list, i+1);
list.remove(list.size()-1);
}
}
}