码迷,mamicode.com
首页 > 其他好文 > 详细

Subsets II

时间:2014-06-04 18:37:55      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

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

bubuko.com,布布扣
class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) 
    {
        vector<int> keys;
        vector<int> count;
        //count pairs
        for(int i=0;i<S.size();i++)
        {
            int j=0;
            for(j=0;j<keys.size();j++)
                if(keys[j]==S[i]) break;
            if(j==keys.size()) 
            {
                keys.push_back(S[i]);
                count.push_back(1);
            }
            else
            {
                count[j]++;
            }
        }
        //sort pairs
        for(int i=0;i<keys.size();i++)
            for(int j=i+1;j<keys.size();j++)
            if(keys[i]>keys[j])
            {
                int tmp=keys[i];
                keys[i]=keys[j];
                keys[j]=tmp;
                tmp=count[i];
                count[i]=count[j];
                count[j]=tmp;
            }
            
        vector<int> v;
        for(int i=0;i<keys.size();i++) v.push_back(0);
        
        vector<vector<int>> result;
        generate(result,keys,count,v,0);
        return result;
    }
    
    void generate(vector<vector<int>>& result,vector<int>& keys,vector<int>& count,vector<int>& v,int dep)
    {
        //add in the result
        if(dep==keys.size())
        {
            vector<int> newv;
            for(int i=0;i<dep;i++)
                for(int j=0;j<v[i];j++)
                    newv.push_back(keys[i]);
            result.push_back(newv);
            return;
        }
        //generate with next key
        for(int i=0;i<=count[dep];i++)
        {
            v[dep]=i;
            generate(result,keys,count,v,dep+1);
        }
    }
};
bubuko.com,布布扣

Subsets II,布布扣,bubuko.com

Subsets II

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/erictanghu/p/3759557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!