本题的题目要求如下:
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]
因为题目中有要求可以访问重复的元素。。所以2下面永远有2,3,6,7.。3下面永远有3,6,7.。
不过倒不用担心无限循环。毕竟有一个target值用来限定总和。。一旦超过了这个值,就要跳出。。
然后是本题的完整代码:
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> tmp;
int end = candidates.size() - 1;
dfs(candidates, 0, end, tmp, target);
return res;
}
private:
vector<vector<int>> res;
void dfs(vector<int> &candidates, int start, int end, vector<int>& tmp, int remain) {
if (remain == 0)
res.push_back(tmp);
else {
int i = start;
while (i <= end && candidates[i] <= remain) {
tmp.push_back(candidates[i]);
dfs(candidates, start, end, tmp, remain-candidates[i]);
tmp.pop_back();
++i;
}
}
}
};