这题自己没想出来看了网上答案,才知道只要在上一题的基础上改用set而不用vector就可以了,set和vector的区别就在于set里没有重复元素,只要用set.insert(*), 会自动识别是否重复。set好牛逼。。
1 class Solution { 2 public: 3 void dfs(int cur, int n, set<vector<int>> &T, vector<int> &tmp, vector<int> S) { 4 if (cur == n) { 5 T.insert(tmp); 6 return; 7 } 8 dfs(cur+1, n, T, tmp, S); 9 tmp.push_back(S[cur]); 10 dfs(cur+1, n, T, tmp, S); 11 tmp.pop_back(); 12 } 13 vector<vector<int> > subsetsWithDup(vector<int> &S) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 sort(S.begin(), S.end()); 17 set<vector<int>> T; 18 vector<vector<int>> ret; 19 if (!S.size()) return ret; 20 vector<int> tmp; 21 dfs(0, S.size(), T, tmp, S); 22 for (set<vector<int>>::iterator it = T.begin(); it != T.end(); it++) 23 ret.push_back(*it); 24 return ret; 25 } 26 };