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

Analysis

这道题应该算Subsets的follow-up,解决input中有重复元素的情况。

不过对策也很直观,就是当遇到重复元素时,跳过相应的backtracking即可。

Solution

Backtracking

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        helper(nums, 0, new ArrayList<Integer>(), res);
        return res;
    }
    private void helper(int[] nums, int start, List<Integer> subset, List<List<Integer>> res) {
        res.add(new ArrayList(subset));
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            subset.add(nums[i]);
            helper(nums, i + 1, subset, res);
            subset.remove(subset.size() - 1);
        }
    }
}

Iterative

public List<List<Integer>> subsetsWithDup(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    result.add(new ArrayList<Integer>());
    int begin = 0;
    for(int i = 0; i < nums.length; i++){
        if(i == 0 || nums[i] != nums[i - 1]) begin = 0;
        int size = result.size();
        for(int j = begin; j < size; j++){
            List<Integer> cur = new ArrayList<Integer>(result.get(j));
            cur.add(nums[i]);
            result.add(cur);
        }
        begin = size;
    }
    return result;
}

Last updated