给你一个整数数组
nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
使用used数组
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length == 0){
return res;
}
boolean[] used = new boolean[nums.length];
List<Integer> path = new ArrayList<>();
Arrays.sort(nums);
dfs(0,nums,used,path,res);
return res;
}
public void dfs(int begin,int[] nums,boolean[] used, List<Integer> path,List<List<Integer>> res){
res.add(new ArrayList<>(path));
for(int i = begin;i < nums.length;i++){
//!used[i-1]代表回溯之前访问过,回溯以后重新置为false
if(i > 0 && !used[i-1] && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
used[i] = true;
dfs(i+1,nums,used,path,res);
path.remove(path.size()-1);
used[i] = false;
}
}
}
本题也可以不使用used数组来去重,因为递归的时候下一个startIndex是i+1而不是0。
如果要是全排列的话,每次要从0开始遍历,为了跳过已入栈的元素,需要使用used。
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length == 0){
return res;
}
List<Integer> path = new ArrayList<>();
Arrays.sort(nums);
dfs(0,nums,path,res);
return res;
}
public void dfs(int begin,int[] nums,List<Integer> path,List<List<Integer>> res){
res.add(new ArrayList<>(path));
for(int i = begin;i < nums.length;i++){
if(i > begin && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
dfs(i+1,nums,path,res);
path.remove(path.size()-1);
}
}
}