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:
For example, given candidate set [2, 3, 6, 7] and
target 7,
A solution set is:
[ [7], [2, 2, 3] ]
Subscribe to see which companies asked this question
c++ code:
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> combs;
vector<int> comb;
combinationSum(combs,comb,candidates,0,target);
return combs;
}
// 自定义函数
void combinationSum(vector<vector<int>>& combs, vector<int>& comb, vector<int>& candidates, int start, int target) {
if (target < 0) return;
else if(target==0) {
combs.push_back(comb);
return;
}
for(int i=start;i<candidates.size();i++) {
comb.push_back(candidates[i]);
combinationSum(combs,comb,candidates,i,target-candidates[i]);// 这里不是i+1,因为可以重用i
comb.pop_back();
}
}
};原文:http://blog.csdn.net/itismelzp/article/details/51623113