lintcode:Combination Sum
原创
©著作权归作者所有:来自51CTO博客作者mb63887cf57331d的原创作品,请联系作者获取转载授权,否则将追究法律责任
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.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
1.dfs(candidates,target,i,tmp,sum);
下次迭代还是从i开始,这样值可以重复
2.怎么避免得到的向量重复,有两种方法:
(1)
if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
continue;
(2)
if(!res.contains(item))
res.add(new ArrayList<Integer>(item));
class Solution {
public:
/**
* @param candidates: A list of integers
* @param target:An integer
* @return: A list of lists of integers
*/
vector<vector<int> >res;
void dfs(vector<int> &candidates, int target,int cur,vector<int> &tmp,int sum){
if(sum>target){
return;
}
if(sum==target){
res.push_back(tmp);
return;
}
for(int i=cur;i<candidates.size();i++){
if(i>0 && candidates[i]==candidates[i-1]){
continue;
}
tmp.push_back(candidates[i]);
sum+=candidates[i];
dfs(candidates,target,i,tmp,sum);//i
sum-=candidates[i];
tmp.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// write your code here
vector<int> tmp;
sort(candidates.begin(),candidates.end());
dfs(candidates,target,0,tmp,0);
return res;
}
};