Combination Sum
Total Accepted: 95000
Total Submissions: 302249
Difficulty: Medium
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.
- 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] ]
Subscribe to see which companies asked this question
Hide Similar Problems
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();
}
}
};