90. Subsets II - Medium

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);
        }
    }
}

 

posted @ 2018-12-06 14:16  fatttcat  阅读(120)  评论(0编辑  收藏  举报