sourcecode

Thursday, January 3, 2013

Subsets (I and II)


Subsets I
Given a set of distinct integers, 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,3], a solution is:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(S.begin(), S.end());
        vector<int> init_mask(S.size(), 0);
        vector<vector<int> > r;
        r.push_back(vector<int>());
        for(int ii = 0; ii < S.size(); ++ii){
            init_mask[ii] = 1;
            vector<int> mask(init_mask);
            do{
                vector<int> subset;
                for(int jj = 0; jj < S.size(); ++jj){
                    if (mask[jj]) subset.push_back(S[jj]);
                }
                r.push_back(subset);
            }while(prev_permutation(mask.begin(),mask.end()));
        }
        return r;
    }
};




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 {
    vector<vector<int> > result;
    map<int,int> us;//unique_s: [val], count
    
    void build(vector<int> line, map<int,int>::iterator it, int depth){
        if (it == us.end() || depth < 0) return;
        for(; it != us.end(); ++it){
            for(int ii = 1; ii <= it->second; ++ii){
                vector<int> temp(line);
                temp.insert(temp.end(), ii, it->first);
                if (depth - ii == 0){
                    result.push_back(temp);
                }else{
                    ++it;
                    build(temp, it, depth - ii);
                    --it;
                }
            }
        }
        return;        
    }
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        result.clear();
        result.push_back(vector<int>());
        if (S.empty()) return result;
        us.clear();
        for(int ii = 0; ii < S.size(); ++ii){
            ++us[S[ii]];
        }
        map<int,int>::iterator it = us.begin();
        for(int ii = 0; ii <= S.size(); ++ii)
            build(vector<int>(), it, ii);
        return result;
    }
};

No comments: