zoukankan      html  css  js  c++  java
  • [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);
        }
    }
  • 相关阅读:
    [JAVA] 运行 java HelloWorld 命令,提示“错误: 找不到或无法加载主类
    「Ubuntu」 终端更新时,报错
    【MATLAB】 运行Simulink时出现报错
    Ubuntu提示boot内存不足
    python+unittest+requests实现接口自动化的方法
    Python + Requests + Unittest接口自动化测试实例分析
    七.测试执行的log读取
    五.DDT测试驱动
    操作json文件
    四.爬取拉勾网实例
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12319838.html
Copyright © 2011-2022 走看看