Saturday, September 20, 2014

LeetCode: Subsets II

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],
  []
]


   #define tr(v, it) for(decltype((v).begin()) (it) = (v).begin(); (it) != (v).end(); (it)++)  

   typedef vector<vector<int> > vvi;  

   vector<vector<int> > subsetsWithDup(vector<int> &S) {  
     set< vector<int> > res;  
     vvi V;  
     int n = S.size();  
     if(n == 0)return V;  
     sort(S.begin(), S.end());  
     for (int i = 0; i < pow(2,n); i++)  
     {  
       vector<int> v;  
       for (int j = 0; j <32; j++)  
       {  
         if(i & (1<<j))v.push_back(S[j]);  
       }  
       res.insert(v);  
     }  
     tr(res, it)  
       V.push_back(*it);  
     return V;  
   }  

No comments:

Post a Comment