LeetCode: Subsets II

来源:互联网 发布:淘宝卖家客服怎么分流 编辑:程序博客网 时间:2024/05/17 02:39

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


class Solution {public:    vector<vector<int> > subsetsWithDup(vector<int> &S) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> rcd;          vector<vector<int> > res;         vector<int> count;        vector<int> s;        sort(S.begin(), S.end());         for(int i = 0; i< S.size(); ++i){            int c = 1;            while(i + 1 < S.size() && S[i] == S[i+1]){                c++;                i++;            }            s.push_back(S[i]);            count.push_back(c);        }        if(S.size() == 0){return res;}                  generate(res, rcd, s, count, 0);          return res;      }    void generate(vector<vector<int> >& res, vector<int> &rcd, vector<int> &S, vector<int> &count, int n){          res.push_back(rcd);        for(int i = n; i< S.size(); ++i){            if(count[i]){                count[i]--;                rcd.push_back(S[i]);                generate(res, rcd, S, count, i);                 rcd.pop_back();                count[i]++;            }        }         return;      } };