• [LC] 90. Subsets II


    Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

    Note: The solution set must not contain duplicate subsets.

    Example:

    Input: [1,2,2]
    Output:
    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]

    Solution 1
    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return res;
            }
            Arrays.sort(nums);
            helper(res, new ArrayList<>(), nums, 0);
            return res;
        }
        
        private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int index) {
            res.add(new ArrayList<>(list));
            for (int i = index; i < nums.length; i++) {
                if (i > index && nums[i] == nums[i - 1]) {
                    continue;
                }
                list.add(nums[i]);
                // use i not index b/c index smaller than i
                helper(res, list, nums, i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> result = new ArrayList<>();
            if (nums == null) {
                return result;
            }
            List<Integer> list = new ArrayList<>();
            Arrays.sort(nums);
            helper(nums, list, 0, result);
            return result;
        }
        
        private void helper(int[] nums, List<Integer> list, int level, List<List<Integer>> result)     {
            if (level == nums.length) {
                result.add(new ArrayList<>(list));
                return;
            }
            // need to add first, skip index and then remove
            list.add(nums[level]);
            helper(nums, list, level + 1, result);
            list.remove(list.size() - 1);
            
            while (level + 1 < nums.length && nums[level] == nums[level + 1]) {
                level += 1;
            }
            helper(nums, list, level + 1, result);
        }
    }
  • 相关阅读:
    Android TTS
    观察者模式(C++实现)
    android 8未知来源app安装
    NotificationChannel
    java底层知识
    Java14
    数据库分区、分库分表
    二叉搜索树的第k大节点
    从上到下按层打印二叉树
    springcloud面试知识点
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12319838.html
Copyright © 2020-2023  润新知