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);
        }
    }
  • 相关阅读:
    linux 常用技巧
    python做本地数据与数据库的校验
    locust性能测试简谈
    正则表达式-将字符串替换成json格式
    正则表达式
    robotframework接口测试案例
    robotframework环境搭建
    python数组
    配置java运行环境
    oracle详细安装教程(附带百度网盘资源)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12319838.html
Copyright © 2011-2022 走看看