Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
class Solution { public: void subset(vector<vector<int>> &res,vector<int> &temp,vector<int> &S,int from) { res.push_back(temp); for(int i=from;i<S.size();i++) { if(i>from&&S[i]==S[i-1])continue; temp.push_back(S[i]); subset(res,temp,S,i+1); temp.pop_back(); } } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> res; res.clear(); vector<int> temp; temp.clear(); int n=S.size(); if(n<1)return res; sort(S.begin(),S.end()); subset(res,temp,S,0); return res; } /* void subset(vector<vector<int>> &res,vector<int> &temp,vector<int> &S,int from) { if(from==S.size()) { for(int i=0;i<res.size();i++) { if(res[i]==temp)return; } res.push_back(temp); return; } temp.push_back(S[from]); subset(res,temp,S,from+1); temp.pop_back(); subset(res,temp,S,from+1); } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> res; res.clear(); vector<int> temp; temp.clear(); int n=S.size(); if(n<1)return res; sort(S.begin(),S.end()); subset(res,temp,S,0); return res; } void subset(vector<vector<int>> &res,vector<int> &temp,vector<int> &S,int from, int to,int k) { if(k==0) { for(int i=0;i<res.size();i++) { if(res[i]==temp)return; } res.push_back(temp); return; } else { if(from>to)return; else { temp.push_back(S[from]); subset(res,temp,S,from+1,to,k-1); temp.pop_back(); subset(res,temp,S,from+1,to,k); return; } } } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> res; res.clear(); vector<int> temp; temp.clear(); int n=S.size(); sort(S.begin(),S.end()); if(n<1)return res; for(int k=0;k<=n;k++) { subset(res,temp,S,0,n-1,k); } return res; } */ };