1 Combination Sum
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.
可以采用递归的方法解决这个问题,当找到一组数之和等于目标后将这组数加入容器,然后返回;当一组数之和大于目标,立即返回;当小于目标继续递归。
void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result)
{
if(sum>target) return;
else if(sum==target)
{
result.push_back(mid);
return;
}
else
{
for(int i=level;i<candidates.size();i++)
{
sum+=candidates[i];
mid.push_back(candidates[i]);
dfscombine(candidates,i,sum,target,mid,result);
mid.pop_back();
sum-=candidates[i];
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> mid;
vector<vector<int> > result;
sort(candidates.begin(),candidates.end());
int level=0,sum=0;
dfscombine(candidates,level,sum,target,mid,result);
return result;
}
2 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.
该题与上一题的区别是给定的数据集中的数据只能用一次,我只需将上题中递归的参数
void dfscombine(vector<int>& candidates,int level,int& sum,int target,vector<int>& mid,vector<vector<int> >& result)
{
if(sum>target) return;
else if(sum==target)
result.push_back(mid);
else
{
for(int i=level;i<candidates.size();i++)
{
sum+=candidates[i];
mid.push_back(candidates[i]);
dfscombine(candidates,i+1,sum,target,mid,result); //保证一个元素只用一次
mid.pop_back();
sum-=candidates[i];
while(i<candidates.size()-1 && candidates[i]== candidates[i+1]) i++; //防止重复
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> mid;
vector<vector<int> > result;
sort(candidates.begin(),candidates.end());
int level=0,sum=0;
dfscombine(candidates,level,sum,target,mid,result);
return result;
}
原文地址:http://blog.csdn.net/zhulong890816/article/details/45766469