题目
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]
求候选元素中所有和为目标值的组合,
候选元素可以多次取,组合不能完全相同。
虽然没有说明,实际所有的候选元素都是不同的。
递归求解。
代码:
class Solution {
vector<vector<int>> ans; //结果
vector<int> temp; //单次结果
public:
void combs(vector<int> &cand,int target,int sum,int begin) //候选集,目标,当前集合的和,当前集合用到的最大序号
{
if(sum==target) //符合要求
{
ans.push_back(temp);
return;
}
for(int i=begin;i<cand.size();i++) //寻找
{
if(sum+cand[i]<=target)
{
temp.push_back(cand[i]);
combs(cand,target,sum+cand[i],i);
temp.pop_back();
}
else
break;
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
ans.clear();
temp.clear();
if(candidates.empty())
return ans;
sort(candidates.begin(),candidates.end()); //!!!需要保证候选集合没有重复元素
combs(candidates,target,0,0);
return ans;
}
};