> For the complete documentation index, see [llms.txt](https://aaronice.gitbook.io/lintcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aaronice.gitbook.io/lintcode/backtracking/subsets-ii.md).

# Subsets II

Medium

Given a collection of integers that might contain duplicates, ***nums***, return all possible subsets (the power set).

**Note:**&#x54;he solution set must not contain duplicate subsets.

**Example:**

```
Input:
 [1,2,2]

Output:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
```

## Analysis

这道题应该算Subsets的follow-up，解决input中有重复元素的情况。

不过对策也很直观，就是当遇到重复元素时，跳过相应的backtracking即可。

## Solution

Backtracking

```java
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        helper(nums, 0, new ArrayList<Integer>(), res);
        return res;
    }
    private void helper(int[] nums, int start, List<Integer> subset, List<List<Integer>> res) {
        res.add(new ArrayList(subset));
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            subset.add(nums[i]);
            helper(nums, i + 1, subset, res);
            subset.remove(subset.size() - 1);
        }
    }
}
```

Iterative

```java
public List<List<Integer>> subsetsWithDup(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    result.add(new ArrayList<Integer>());
    int begin = 0;
    for(int i = 0; i < nums.length; i++){
        if(i == 0 || nums[i] != nums[i - 1]) begin = 0;
        int size = result.size();
        for(int j = begin; j < size; j++){
            List<Integer> cur = new ArrayList<Integer>(result.get(j));
            cur.add(nums[i]);
            result.add(cur);
        }
        begin = size;
    }
    return result;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/backtracking/subsets-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
