leetcode : Subsets I&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.

 I 和 II 的区别在于S 是否包含重复元素。用动态规划,每次从S中读出连续n个相同的正数A,然后对当前结果集的每个子集分别在后面加入1个,2个,3个。。。n个A之后将这些新的子集加入结果集中。I可以看成II的特殊情况。下面是II的AC代码。

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int>> ret;
        vector<int> nul;
        ret.push_back(nul);
        if(!S.size())
            return ret;
        
        int count = 0;
        sort(S.begin(), S.end());
        while(count < S.size()){
            int dup = 1, n = S[count];
            while(count < S.size() - 1 && n == S[count + 1]){
                ++dup;
                ++count;
            }
            
            auto temp = ret;
            for(int i = 0; i < dup; ++i){
                for(auto &w : temp)
                    w.push_back(n);
                for(auto &w : temp)
                    ret.push_back(w);
            }
            ++count;
        }
    }
};

 

posted on 2014-11-22 20:34  远近闻名的学渣  阅读(100)  评论(0)    收藏  举报

导航