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]
1:特殊情况;2:对数组进行按升序列进行排序;3:采用递归的方式,注意递归结束的条件;4:获得满足提交的组合
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int> > result;
if(candidates.size() <= 0)
{
return result;
}
sort(candidates.begin(), candidates.end());
vector<int> temp;
combinationSumCore(candidates, target, 0, temp, result);
return result;
}
void combinationSumCore(vector<int> &candidates, int target, int index, vector<int> &temp, vector<vector<int> > &result)
{
if(index == candidates.size() || candidates[index] > target)
{
return;
}
if(candidates[index] == target)
{
temp.push_back(candidates[index]);
result.push_back(temp);
temp.pop_back();
return;
}
else
{
temp.push_back(candidates[index]);
combinationSumCore(candidates, target - candidates[index], index , temp, result);
temp.pop_back();
combinationSumCore(candidates, target, index+1, temp, result);
}
}