LeetCode-Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

class Solution {
public:
   void sub(vector<int>& c,int len,int target ,
        map<pair<int,int>,vector<vector<int> > > &m1){
        if(m1.find(pair<int,int>(len,target))!=m1.end()){
            return;
        }
        else{
            if(target==0){
                m1[pair<int,int>(len,target)]=vector<vector<int> >(1);
                return;
            }
            if(len==1){
                if(target==c[0]){
                    vector<vector<int>>& vec=m1[pair<int,int>(len,target)];
                    vec.resize(1);
                    vec[0].push_back(c[0]);
                    return;
                }
                else{
                    return;
                }
            }
            if(c[len-1]>target){
                sub(c,len-1,target,m1);
                m1[pair<int,int>(len,target)]=m1[pair<int,int>(len-1,target)];
                return;
            }
            else{
                sub(c,len-1,target,m1);
                m1[pair<int,int>(len,target)]=m1[pair<int,int>(len-1,target)];
                vector<vector<int>>& vec=m1[pair<int,int>(len,target)];
                
                sub(c,len-1,target-c[len-1],m1);
                vector<vector<int>>& vec1=m1[pair<int,int>(len-1,target-c[len-1])];
                    for(int j=0;j<vec1.size();j++){
                        vec.push_back(vec1[j]);
                        vec[vec.size()-1].push_back(c[len-1]);
                    }
                return;
            }
        }
    }
    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        set<int> s;
        for(int i=0;i<candidates.size();i++)s.insert(candidates[i]);
        vector<int> iv(s.begin(),s.end());
        map<pair<int,int>,vector<vector<int> > > m1;
        sub(candidates,candidates.size(),target,m1);
        vector<vector<int> >& ret= m1[pair<int,int>(candidates.size(),target)];
        set<vector<int> > alp;
        for(int i=0;i<ret.size();i++){
            sort(ret[i].begin(),ret[i].end());
            alp.insert(ret[i]);
        }
        vector<vector<int> >beta(alp.begin(),alp.end());
        return beta;
    }
};
View Code

 

posted @ 2013-09-24 00:44  懒猫欣  阅读(148)  评论(0编辑  收藏  举报