> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Subsets II Python Solution with Tests

> Tested Python solution for LeetCode 90 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 90, Medium. Topics: Array, Backtracking, Bit Manipulation. [View on LeetCode](https://leetcode.com/problems/subsets-ii/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 90   # by problem number
lcpy gen -s subsets_ii   # by problem name
```

## 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**.

### Examples

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

```
Input: nums = [0]
Output: [[],[0]]
```

### Constraints

* 1 \<= nums.length \<= 10
* -10 \<= nums\[i] \<= 10

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subsets_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/subsets_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * 2^n)
    # Space: O(n) recursion stack
    def subsets_with_dup(self, nums: list[int]) -> list[list[int]]:
        nums.sort()
        result: list[list[int]] = []
        subset: list[int] = []

        def backtrack(start: int) -> None:
            result.append(list(subset))
            for i in range(start, len(nums)):
                # Skip duplicates at the same depth to avoid duplicate subsets
                if i > start and nums[i] == nums[i - 1]:
                    continue
                subset.append(nums[i])
                backtrack(i + 1)
                subset.pop()

        backtrack(0)
        return result
```

## Complexity

| Time        | Space                |
| ----------- | -------------------- |
| O(n \* 2^n) | O(n) recursion stack |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
