leetcode 组合题

1.Subsets
代码1:
class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int>>v;
        vector<int>v2(S.size(),0);
        sort(S.begin(),S.end());
        subset(v,S,0,v2);
        return v;        
    }
    void subset(vector<vector<int>> &v,vector<int> &S,int cur,vector<int> &v2)
    {
        if(cur==S.size())
        {
            vector<int>child;
            for(int i=0;i<cur;i++)
            {
              if(v2[i])
              child.push_back(S[i]);
            }//另外一道题SubSetII,此处加上if(count(v.begin(),v.end(),child)==0)
           v.push_back(child); 
           return;
        }
        v2[cur]=1;
        subset(v,S,cur+1,v2);
        v2[cur]=0;
        subset(v,S,cur+1,v2);
    }
};

 较好的解法:

class Solution {
public:
vector<vector<int>>v;
vector<int>temp;
    vector<vector<int> > subsetsWithDup(vector<int> &S) 
    {
       sort(S.begin(),S.end());
       v.clear();
       temp.clear();
       dfs(S,0);
       return v;
    }
    void dfs(vector<int> &S,int dep)
    {
        v.push_back(temp);
        for(int i=dep;i<S.size();i++)
       {  
          if(i!=dep&&S[i]==S[i-1])continue; //SubsetsII 添加代码
          temp.push_back(S[i]);		  
		  dfs(S,i+1);
	      temp.pop_back();
	   }        
    }
};

 

posted @ 2013-09-09 20:57  代码改变未来  阅读(246)  评论(0编辑  收藏  举报