0
点赞
收藏
分享

微信扫一扫

LeetCode 90 子集 II(Java 标准回溯算法 天然无添加)

幺幺零 2022-01-28 阅读 55

题目:

示例1:

示例2:

提示:

解题代码:

class Solution {
	// 本题就是在 LeetCode 78 子集的基础上加了去重的操作(两步: 排序+去重)
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> path = new ArrayDeque<>();
        int index = 0;
        int depth = 0;
        int len = nums.length;
        // 排序
        Arrays.sort(nums);
        dfs(nums, res, path, index, depth, len);
        return res;
    }

    public void dfs(int[] nums, List<List<Integer>> res, Deque<Integer> path, int index, int depth, int len){
        res.add(new ArrayList(path));
        if(len == depth){
            return;
        }

        for(int i = index; i < nums.length; i++){
        	// 去重
            if(i > index && nums[i] == nums[i-1])
                continue;
            path.addLast(nums[i]);
            dfs(nums, res, path, i+1, depth+1, len);
            path.removeLast();
        }
    }
}

请添加图片描述
LeetCode 78 子集(Java 标准回溯算法 天然无添加)

举报

相关推荐

0 条评论