AAlgoLoopSpaced repetition for LeetCode
MEDIUMBacktrackingLeetCode ↗

Subsets II

The key idea

Sort nums first so equal values sit next to each other, then inside the choose-loop skip a value when i > start and nums[i] == nums[i-1]. That skip drops only the duplicate sibling branches at one depth while still letting a repeated value extend the current path, so every distinct subset is generated exactly once.

Problem

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

The solution set must not contain duplicate subsets. Return the solution in any order.

Constraints

Examples

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

Complexity

Time: O(n * 2^n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Backtracking problems