Subsets II

MediumArrayHash TableBacktracking

Description

Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets.

Examples

Input:nums = [1,2,2]
Output:[[],[1],[1,2],[1,2,2],[2],[2,2]]
Explanation:

With nums = [1,2,2], generate subsets by including 0, 1, or 2 copies of the duplicate '2', combined with whether to include '1'. The subsets are: [] (empty), [1], [2], [1,2], [2,2], and [1,2,2]. Note that [2] appears once, not twice, to avoid duplicate subsets.

Input:nums = [4,4,4]
Output:[[],[4],[4,4],[4,4,4]]
Explanation:

When all elements are identical, it is possible to only form subsets by choosing 0, 1, 2, or all 3 elements. Since all elements are the same value (4), this gives subsets of increasing lengths but no other variations.

Input:nums = [1,2,3,3]
Output:[[],[1],[1,2],[1,2,3],[1,2,3,3],[1,3],[1,3,3],[2],[2,3],[2,3,3],[3],[3,3]]
Explanation:

Sorting gives [1,2,3,3]. For the unique elements 1 and 2, It is possible to include or exclude each. For the duplicate 3's, It is possible to include 0, 1, or 2 copies. This yields subsets like [1,2,3,3] (all elements), [1,3] (one 3), [3,3] (both 3's, no 1 or 2), and [] (empty). The 12 unique subsets avoid duplicates like having two separate [3] entries.

Constraints

  • 1 ≤ nums.length ≤ 10
  • -10 ≤ nums[i] ≤ 10

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!