• 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],
      []
    ]

    和78. Subsets不同的是可以有重复值,关键在于如何去重:

    首先把数组排序;并且,每次recursive call的时候,判断一下当前元素和上一个元素是否相同,相同则跳过

    reference: https://www.cnblogs.com/yrbbest/p/4437152.html

    time: O(n * 2 ^ n), space: O(2 ^ n)

    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);
            dfs(nums, 0, new ArrayList<>(), res);
            return res;
        }
        
        private void dfs(int[] nums, int index, List<Integer> list, List<List<Integer>> res) {
            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]);
                dfs(nums, i + 1, list, res);
                list.remove(list.size() - 1);
            }
        }
    }

    另一种写法:

    time: O(n * 2 ^ n), space: O(2 ^ n)

    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(nums);
            backtracking(nums, 0, new ArrayList<>(), res);
            return res;
        }
        
        private void backtracking(int[] nums, int idx, List<Integer> tmp, List<List<Integer>> res) {
            if(!res.contains(tmp)) res.add(new ArrayList<>(tmp));
            for(int i = idx; i < nums.length; i++) {
                tmp.add(nums[i]);
                backtracking(nums, i+1, tmp, res);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
  • 相关阅读:
    USACO Section 2.2 Subset Sums
    九度 1399 名侦探柯南
    九度 1416 猴子吃坚果
    pch文件的使用(原作者太逗了)
    线程同步
    extern "c"
    进程与线程
    排序算法代码汇总
    Linux Shell 常用命令与目录分区的学习总结 (开始学习linux)
    堆和栈
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10076471.html
Copyright © 2020-2023  润新知