Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
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 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
解法:
由题意为set知,集合应该没有重复元素;用回溯法。
注意,每个元素可以取多次,
void combinationCore(vector<int> &candi,int target,int begin,vector<int> &tempresult,vector<vector<int> > &results){
if(target==0){//target==0,说明已经找到一个可行解
results.push_back(tempresult);
}
else{
int size=candi.size();
for(int i=begin;i<size&&target>=candi[i];++i){
//target>=candi[i],因为同一个元素可以取多次,则i从begin开始,且下一个也是从i开始,
tempresult.push_back(candi[i]);
combinationCore(candi,target-candi[i],i,tempresult,results);
tempresult.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> results;
int size=candidates.size();
if(size==0||target<=0)
return results;
vector<int> temp;
sort(candidates.begin(),candidates.end());//must
combinationCore(candidates,target,0,temp,results);
return results;
}