标签:collection positive including solution contain
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]
解法:
注意,这题里是用collection 描述C,且给出的例子里有重复元素;题意要求每个元素只能使用一次,则回溯时,
下次应该从i+1开始,
为了去重(数组已经排序),,
void combinationCore(vector<int> &candi,int target,int begin,vector<int> &tempresult,vector<vector<int>> &results){
if(target==0)
results.push_back(tempresult);
else{
int size=candi.size();
for(int i=begin;i<size&&target>=candi[i];++i){
if(i==begin||candi[i]!=candi[i-1]){
//这里i==begin||candi[i]!=candi[i-1],需要注意,因为每次有i==begin,则每次递归,不管这个元素和上一个元素是否相等都会进行下续combinationCore,这能保证如果有连续的2 2 2在求6时可以成立,
但一旦第二次for循环,就要看是否和前一个相等,如果相等,则不处理;因为如果后续能得到解,则必然在第一次for循环时已经得到了。再进行就会重复。
tempresult.push_back(candi[i]);
combinationCore(candi,target-candi[i],i+1,tempresult,results);//这里可以保证每个元素只取一次,因为下次是从i+1开始,
tempresult.pop_back();
}
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
int size=candidates.size();
vector<vector<int>> results;
vector<int> temp;
if(size==0||target<=0)
return results;
sort(candidates.begin(),candidates.end());
combinationCore(candidates,target,0,temp,results);
return results;
}
标签:collection positive including solution contain
原文地址:http://searchcoding.blog.51cto.com/1335412/1694495