sagelearnai

Subsets II

Difficulty: Medium · Pattern: Backtracking · LeetCode #90

Given an integer array nums that may contain duplicates, return all possible subsets, with no duplicate subsets. Any order is accepted.

Examples

text
[1,2,2]  →  [[],[1],[1,2],[1,2,2],[2],[2,2]]
[0]      →  [[],[0]]

Hints

  1. Without duplicates this is plain Subsets. What creates the duplicate subsets?
  2. Choosing the first 2 vs the second 2 at the same position of the recursion tree produces the same subset. Sort, then skip equal siblings.

Approach

Sort nums. backtrack(start) records the current path, then for i from start on:

text
if i > start and nums[i] == nums[i-1]: continue     # same value already tried at this depth
path.append(nums[i]); backtrack(i + 1); path.pop()

The condition i > start (not i > 0) is the subtle part. It skips duplicates among siblings (choices at the same depth) but still lets a duplicate be picked as the next element, so [2,2] is produced. This "sort + skip equal siblings" rule is the standard de-duplication for Combination Sum II and Permutations II too.

Complexity

Time: O(n · 2ⁿ). Space: O(n) recursion besides the output.

Python solution
def subsetsWithDup(nums):
    nums = sorted(nums)
    res, path = [], []
    def bt(start):
        res.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            bt(i + 1)
            path.pop()
    bt(0)
    return res
JavaScript solution
function subsetsWithDup(nums) {
  const a = [...nums].sort((x, y) => x - y), res = [], path = [];
  const bt = (start) => {
    res.push([...path]);
    for (let i = start; i < a.length; i++) {
      if (i > start && a[i] === a[i - 1]) continue;
      path.push(a[i]); bt(i + 1); path.pop();
    }
  };
  bt(0);
  return res;
}