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, a1 ≤ a2 ≤ … ≤ 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] 

C++实现代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    vector<vector<int> > combinationSum2(vector<int> &num, int target){
        if(num.empty())
            return vector<vector<int> >();
        sort(num.begin(),num.end());
        vector<vector<int> > ret;
        vector<int> path;
        combination(num,0,target,ret,path);
        return ret;
    }

    void combination(vector<int> &candidates,int start,int target,vector<vector<int> > &ret,vector<int> &path)
    {
        if(target<0)
            return;
        if(target==0)
        {
            ret.push_back(path);
            return;
        }
        int i;
        for(i=start;i<(int)candidates.size();i++)
        {
            if(i>start&&candidates[i]==candidates[i-1])
                continue;
            path.push_back(candidates[i]);
            combination(candidates,i+1,target-candidates[i],ret,path);
            path.pop_back();
        }
    }
};

int main()
{
    Solution s;
    vector<int> vec={0,0,10,1,2,7,6,1,5};
    vector<vector<int> > result=s.combinationSum2(vec,8);
    for(auto a:result)
    {
        for(auto v:a)
            cout<<v<<" ";
        cout<<endl;
    }
}

运行结果:

posted @ 2014-11-27 09:59  Jessica程序猿  阅读(180)  评论(0编辑  收藏  举报