# 90.Subsets II (M)

## 1.Description(Medium)

Given a list of numbers that may has duplicate numbers, return all possible subsets

### Notice

* Each element in a subset must be in \_non-descending \_order.
* The ordering between two subsets is free.
* The solution set must not contain duplicate subsets.

**Example**

If S =`[1,2,2]`, a solution is:

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

## 2.Code

与subset 相比，区别只在于去重。对于当前字符，如果下一个字符与之相等，则过滤掉。与combination sum I II 的区别相同。

```
public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> S){
        ArrayList<ArrayList<Integer>> result=new ArrayList<>();
        if(S==null || S.size()==0){
            return result;
        }
        ArrayList<Integer> path=new ArrayList<Integer>();
        Collections.sort(S);
        dfs(S,0,path,result);
        return result;        
    }

    public void dfs(ArrayList<Integer> S,int startindex,ArrayList<Integer> path,ArrayList<ArrayList<Integer>> result){
        result.add(new ArrayList<Integer>(path));
        for(int i=startindex;i<S.size();i++){
            if(i!=startindex && S.get(i)==S.get(i-1)){
                continue;
            }
            path.add(S.get(i));
            dfs(S,i+1,path,result);
            path.remove(path.size()-1);
        }
    }
```


---

# Agent Instructions: 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://junnie.gitbook.io/nine-chapter/4.depth-first-search/18.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.
