LeetCode每日一题:子集 2

问题描述

Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.

For example,
If S =[1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

问题分析

这一题我直接拿上题的代码跑了一遍,像[1,1],最后的答案是{[1],[1,1],[1],[]}存在重复的子集,所以我们在dfs的时候去掉相连的重复的元素就可以了

代码实现

 public ArrayList> subsetsWithDup(int[] num) {
        ArrayList> result = new ArrayList<>();
        if (num.length == 0) return result;
        ArrayList list = new ArrayList<>();
        Arrays.sort(num);
        dfsSubsets2(num, 0, list, result);
        return result;
    }

    private void dfsSubsets2(int[] num, int start, ArrayList list, ArrayList> result) {
        result.add(new ArrayList(list));
        for (int i = start; i < num.length; i++) {
            list.add(num[i]);
            dfsSubsets(num, i + 1, list, result);
            list.remove(list.size() - 1);
            while (i < num.length - 1 && num[i] == num[i + 1])//跳过重复元素
                i++;
        }
    }

你可能感兴趣的:(LeetCode每日一题:子集 2)