Skip to content

Instantly share code, notes, and snippets.

@srashee
Created April 4, 2019 01:48
Show Gist options
  • Select an option

  • Save srashee/12bc60a5e91d23fbbb55262e2f563b70 to your computer and use it in GitHub Desktop.

Select an option

Save srashee/12bc60a5e91d23fbbb55262e2f563b70 to your computer and use it in GitHub Desktop.
class Solution {
public:
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
std::sort(candidates.begin(), candidates.end());
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
if (!target) {
res.push_back(combination);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment