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 private: 3 vector<vector<int> > ret; 4 bool canUse[100]; 5 public: 6 void dfs(int dep, int maxDep, vector<int> &num, vector<int> a, int start) 7 { 8 ret.push_back(a); 9 10 if (dep == maxDep) 11 return; 12 13 for(int i = start; i < num.size(); i++) 14 if (i == 0) 15 { 16 canUse[i] = false; 17 vector<int> b(a); 18 b.push_back(num[i]); 19 dfs(dep + 1, maxDep, num, b, i + 1); 20 canUse[i] = true; 21 } 22 else 23 { 24 if (num[i] == num[i-1] && canUse[i-1]) 25 continue; 26 27 canUse[i] = false; 28 vector<int> b(a); 29 b.push_back(num[i]); 30 dfs(dep + 1, maxDep, num, b, i + 1); 31 canUse[i] = true; 32 } 33 } 34 35 vector<vector<int> > subsetsWithDup(vector<int> &S) { 36 // Start typing your C/C++ solution below 37 // DO NOT write int main() function 38 sort(S.begin(), S.end()); 39 ret.clear(); 40 memset(canUse, true, sizeof(canUse)); 41 vector<int> a; 42 dfs(0, S.size(), S, a, 0); 43 return ret; 44 } 45 };