Leetcode90. 子集 II

题目传送:https://leetcode.cn/problems/subsets-ii/

运行效率:
Leetcode90. 子集 II_第1张图片
代码如下:

   public static List<List<Integer>> subsetsWithDup(int[] nums) {
   //先对数组进行升序排列
        Arrays.sort(nums);
        //hashset的作用是为了做去重操作
        HashSet<String> set = new HashSet<>();
        List<List<Integer>> lists = subsetsWithDupOnSet(nums, set);
        return lists;
    }

    public static List<List<Integer>> subsetsWithDupOnSet(int[] nums, HashSet<String> set) {
        List<List<Integer>> result = new ArrayList<>();
        //处理边界情况
        if (nums.length == 1) {
            List<Integer> list1 = new ArrayList<>();
            result.add(list1);
            set.add(Arrays.toString(list1.toArray()));
            List<Integer> list2 = new ArrayList<>();
            list2.add(nums[0]);
            set.add(Arrays.toString(list2.toArray()));
            result.add(list2);
            return result;
        }
        //递归解法
        int[] restNums = Arrays.copyOfRange(nums, 0, nums.length - 1);
        List<List<Integer>> lists = subsetsWithDupOnSet(restNums,set);
        result.addAll(lists);
        for (List<Integer> list : lists) {
            List<Integer> list1 = new ArrayList<>();
            list1.addAll(list);
            list1.add(nums[nums.length - 1]);
            if (!set.contains(Arrays.toString(list1.toArray()))) {
                set.add(Arrays.toString(list1.toArray()));
                result.add(list1);
            }
        }
        return result;
    }

你可能感兴趣的:(数据结构和算法,算法,leetcode,数据结构)