leetcode Subsets II

来源:互联网 发布:儿童画画的软件 编辑:程序博客网 时间:2024/06/05 00:59

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

Take advantage of the order to eliminate the duplicate sets. The following is the code: 

class Solution { public:  vector<vector<int>> res;  void subsets(vector<int>& S, int start, vector<int>& numset) {    if (start >= S.size())       return;      numset.push_back(S[start]);    res.push_back(numset);    subsets(S, start + 1, numset);    numset.pop_back();        while (start + 1 < S.size() && S[start] == S[start + 1])      ++start;    if (start + 1 < S.size())      subsets(S, start + 1, numset);  }  vector<vector<int> > subsetsWithDup(vector<int> &S) {    // Note: The Solution object is instantiated only once and is reused by each test case.    res.clear();    vector<int> numset;    res.push_back(numset);    sort(S.begin(), S.end());    subsets(S, 0, numset);    return res;  }};

 Non-recursive version, but this is wrong, too:

class Solution {public:  vector<vector<int> > subsetsWithDup(vector<int> &S) {    // Note: The Solution object is instantiated only once and is reused by each test case.    vector<vector<int> > res;    vector<int> numset;    int start = 0, len = S.size(), i, j;    vector<int> status(len, -1);    res.push_back(numset);    sort(S.begin(), S.end());    while (start > -1) {      if (start == len)        --start;      if (status[start] == -1) {        ++status[start++];      }      else if (status[start] == 0) {        ++status[start];        numset.push_back(S[start++]);         res.push_back(numset);      }      else {        status[start] = -1;        numset.pop_back();        --start;      }    }    res.resize(distance(res.begin(),unique(res.begin(), res.end())) );    return res;  }  };

The right code is:


class Solution { public:  vector<vector<int> > subsetsWithDup(vector<int> &S) {    int size = S.size(), i = 0, j;    vector<int> status(size, -1);    vector<vector<int> > res;    vector<int> cur;        sort(S.begin(), S.end());    res.push_back(cur);    while (i > -1) {      if (i == size) {        --i;      }      else if (status[i] == -1) {        ++status[i++];        }      else if (status[i] == 0) {        ++status[i];        cur.push_back(S[i++]);        res.push_back(cur);      }      else {        status[i--] = -1;        cur.pop_back();      }      }        sort(res.begin(), res.end());    res.resize(distance(res.begin(), unique(res.begin(), res.end())));    return res;  }};


原创粉丝点击