【力扣刷题总结之90. 子集 II】

相关标签


一、题目要求 

二、题解和代码实现 

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]
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值