相关标签
一、题目要求
二、题解和代码实现
1.题解
2.代码实现
代码如下(示例):
class Solution {
List<List<Integer>> list = new ArrayList<>();//最终返回结果
Deque<Integer> DupDfsres = new ArrayDeque<Integer>();//创建栈
boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
int len = nums.length;
if (len==0){
return null;
}
used = new boolean[len];
Arrays.sort(nums);//去重要先排序
subsetsWithDupDfs(nums,len,0);
return new ArrayList<>(list);
}
private void subsetsWithDupDfs(int[] nums, int len, int index) {
list.add(new ArrayList<>(DupDfsres));
for (int i = index; i <len; i++) {
// used[i - 1] == true,说明同一树支candidates[i - 1]使用过
// used[i - 1] == false,说明同一树层candidates[i - 1]使用过
// 而我们要对同一树层使用过的元素进行跳过
if (i>0 && used[i-1]==false && nums[i] == nums[i-1]){
continue;
}
DupDfsres.addLast(nums[i]);//这里是添加这一层的num[index]进res
used[i]=true;//记录当前i的值被使用了
subsetsWithDupDfs(nums, len, i+1);//这里是递归到下一层
used[i]=false;//取消当前i的值被使用
DupDfsres.removeLast();//上面的递归结束后,说明已经到叶子结点过,然后就要回溯,删除刚刚添加的num[index]
}
}
}