子集 II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

思路

针对数组的每一个数有‘取’与‘不取’两种情况,如下图


image.png
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> L = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(nums);
        subset(nums, L, list, 0);
        return L;
    }
    
    public static void subset(int[] nums, List<List<Integer>> L, List<Integer> list, int index) {

        if (index == nums.length) {
            for (int i = 0; i < L.size(); i++) {
                if (L.get(i).equals(list)) {
                    return;
                }
            }
            L.add(new ArrayList(list));

            return ;
        }

        list.add(nums[index]);
        subset(nums, L, list, index + 1);
        list.remove(list.size() - 1);
        subset(nums, L, list, index + 1);
    }
}
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> L = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        HashSet<List<Integer>> set = new HashSet<List<Integer>>();
        Arrays.sort(nums);
        subset(nums, set, list, 0);

        return new ArrayList<List<Integer>>(set);
    }
    
    public static void subset(int[] nums, HashSet<List<Integer>> set, List<Integer> list, int index) {

        if (index == nums.length) {
            set.add(new ArrayList(list));
            return ;
        }

        list.add(nums[index]);
        subset(nums, set, list, index + 1);
        list.remove(list.size() - 1);
        subset(nums, set, list, index + 1);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 题目给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集...
    HITZGD阅读 195评论 0 0
  • 给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。说明:解集不能包含重复的子集。 示...
    vbuer阅读 172评论 0 0
  • 算法思想贪心思想双指针排序快速选择堆排序桶排序荷兰国旗问题二分查找搜索BFSDFSBacktracking分治动态...
    第六象限阅读 4,888评论 0 0
  • 今天我给大家分享的内容是如何打造高逼格朋友圈对于我们来说。朋友圈就是我们的门面。再分享之前我想问你们一个问题,你知...
    棒棒糖孙静阅读 903评论 0 0
  • 有关这个问题,我和自家两姑娘经过20秒钟激烈地讨论就立刻达成一致,能想啥,想发财呗。然后接下来的两小时我们都在兴奋...
    猫猫仙儿阅读 219评论 0 1

友情链接更多精彩内容