class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum) {
if(target == sum) {
result.push_back(path);
return;
} else if(sum > target) {
return;
}
for(int i = 0; i < candidates.size(); i++) {
if(path.size() == 0 || path[path.size()-1] <= candidates[i]) {
path.push_back(candidates[i]);
backtracking(candidates, target, sum + candidates[i]);
path.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, target, 0);
return result;
}
};
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
if(target == sum) {
result.push_back(path);
return;
}
// Don't need to backtracking if already above target
for(int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
path.push_back(candidates[i]);
backtracking(candidates, target, sum + candidates[i], i);
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); // Need sort
backtracking(candidates, target, 0, 0);
return result;
}
};