题目:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
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]
vector<vector<int> > combinares;
bool combinationsum(vector<int> input, vector<int> candidates, int begin, int target)
{
if(target<0) return true;
if(target==0)
{
combinares.push_back(candidates);
return true;
}
int flag=false;
for(int i=begin; i<input.size(); i++)
{
if(i>begin &&input[i]==input[i-1] ) continue;
candidates.push_back(input[i]);
flag=combinationsum(input, candidates, i+1, target-input[i]);//要指到下一个元素,不能重复
candidates.pop_back();
if(flag) break;
}
return false;
}
vector<vector<int> > combinationSum2(vector<int> &candidates, int target)
{
if(candidates.size()<1) return combinares;
vector<int> candidate;
sort(candidates.begin(), candidates.end());
combinationsum(candidates, candidate, 0, target);
return combinares;
}