30 Day Challenge Day 14 | Leetcode 39. Combination Sum
题解
Medium | Backtracking
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> sols;
vector<int> sol;
helper(candidates, target, 0, 0, sol, sols);
return sols;
}
void helper(vector<int>& candidates, int target, int index, int sum, vector<int>& sol, vector<vector<int>>& sols) {
if(sum == target) {
sols.push_back(sol);
return;
}
if(sum > target) return;
for(int i = index; i < candidates.size(); i++) {
sol.push_back(candidates[i]);
helper(candidates, target, i, sum+candidates[i], sol, sols);
sol.pop_back();
}
}
};