Subsets II
MediumNeetCode 150 BacktrackingProblem
You are given an array nums that may contain the same number more than once. Return every
possible subset, but do not return two subsets that hold the same numbers (the order inside a subset does not matter).
The subsets may be returned in any order.
Constraints
- 1 ≤ nums.length ≤ 10
- -10 ≤ nums[i] ≤ 10
Examples: pick one to animate
Solutions
Time: At most 2ⁿ subsets are built, each copied into the answer for up to n work. Skipping repeats only removes branches.
Space: Besides the output, the recursion is at most n + 1 calls deep and the path holds at most n numbers.
Sort so equal numbers are neighbours. Build subsets with the usual start-index backtracking, but inside one loop skip a number that equals the one before it (unless it is the first choice of the loop). The first copy already covers every subset that starts that way.