Subsets II
Master this topic with zero to advance depth.
Subsets II
Handling Duplicates
When the input array contains duplicates, the standard power set logic generates duplicate subsets. To avoid this, we must sort the array and skip identical elements during the recursion.
The Skip Condition
If nums[i] == nums[i-1] and we are at the same recursive level (not following the inclusion branch), we skip the current element to avoid repeating the same starting subset.
Generate all possible subsets of an integer array that may contain duplicates. Includes visual duplicate-skipping trace.
Examples
Level I: Backtracking with Sorting
Intuition
Sort and skip duplicates to ensure uniqueness.
Sort the array first. In the loop-based backtracking, if i > start and nums[i] == nums[i-1], we skip to the next iteration.
Detailed Dry Run
nums=[1,2,2], start=1
1. i=1, pick nums[1]=2 -> subset [1,2]
2. i=2, nums[2]==nums[1], skip!Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.