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],
  []
]
class Solution {
public:
    void mySubSets(vector<vector<int> > & ans, vector<pair<int,int> > & S, vector<int> & A){    
        ans.push_back(A);
        
        //这里的逻辑判断是关键
        int j = 0, c = 0;
        if (A.size()){
            for(int k = 0; k < A.size(); k++){
                if (A[k] == A[A.size() -1]){
                    c++;
                }
            }
            for(; j < S.size(); j++){
                if (S[j].first == A[A.size() -1] && S[j].second > c){
                    break;
                }else if (S[j].first > A[A.size() -1]){
                    break;
                }
            }
        }
        
        for(int i = j; i < S.size();i++){
            A.resize(A.size() + 1);
            A[A.size() -1] = S[i].first;
            mySubSets(ans,S,A);
            A.resize(A.size() -1);
        }    
    }
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<int> A;
        vector<pair<int,int> > M;
        vector<vector<int> > ans;
        if (S.empty()){
            return ans;
        }
        sort(S.begin(),S.end());
        int counter = 1,i = 1;
        for(; i < S.size(); i++){
            if (S[i] == S[i-1]){
                counter ++;
            }else{
                M.push_back(make_pair(S[i-1],counter));
                counter = 1;
            }
        }
        M.push_back(make_pair(S[i-1],counter));
        mySubSets(ans,M,A);
        return ans;
    }
};

 

posted @ 2013-07-13 08:22  一只会思考的猪  阅读(161)  评论(0编辑  收藏  举报