Combination Sum
Q: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]
A: DFS问题。
注意迭代结束条件:target==0,发现解; target<0,无解
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
vector<int> path;
sort(candidates.begin(),candidates.end());
combinationsum_aux(0,candidates,target,path,result);
return result;
}
bool combinationsum_aux(int curPos,vector<int>& candidates,int target,vector<int>& path,vector<vector<int> >& result)
{
if(target==0)
{
result.push_back(path);
return true;
}else if(target<0)
return false;
for(int i=curPos;i<candidates.size();i++)
{
path.push_back(candidates[i]);
if(!combinationsum_aux(i,candidates,target-candidates[i],path,result)) //注意i不是加一,因为数可以无限次被使用。这里还做了剪枝,当返回false,说明当前层()已经完成了搜索,返回到上层。
{
path.pop_back();
break;
}
path.pop_back();
}
return true;
}
浙公网安备 33010602011771号