Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
每个元素都有两种选择,加入或不加入集合。所以,深度优先搜索解题。
注意,不能有重合的集合。所以,相同的元素我们只需控制它加入集合的个数即可。
1 class Solution {
2 public:
3 vector<vector<int> > subsetsWithDup(vector<int> &S) {
4 // Start typing your C/C++ solution below
5 // DO NOT write int main() function
6 vector<vector<int>> v;
7 vector<int> tmp;
8 if(S.size()==0)
9 return v;
10 sort(S.begin(),S.end());
11 DepthFirst(S,v,tmp,0);
12 return v;
13 }
14 void DepthFirst(vector<int> &S , vector<vector<int> > &v ,vector<int> &tmp , int depth)
15 {
16 if(depth == S.size())
17 {
18 v.push_back(tmp);
19 return;
20 }
21 int i = depth;
22 while(i+1 < S.size() && S[i] == S[i+1])
23 {
24 i++;
25 }
26 for(int j = 0;j <= i - depth +1;j++)
27 {
28 for(int k = 1; k <= j;k++)
29 tmp.push_back(S[depth]);
30 DepthFirst(S,v,tmp,i+1);
31 for(int k = 1; k <= j;k++)
32 tmp.pop_back();
33 }
34 }
35 };