fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Solution {
  6. public:
  7. void helper(const vector<int>& curr_list, int target,
  8. const vector<int>& candidates, int start_index,
  9. vector<vector<int>>* res) {
  10. if (curr_list.size() == 3) {
  11. if (target == 0) {
  12. res->push_back(curr_list);
  13. }
  14. return;
  15. }
  16.  
  17. for (int i = start_index; i < candidates.size(); i++) {
  18. int diff = target - candidates[i];
  19. auto new_vec = curr_list;
  20. new_vec.push_back(candidates[i]);
  21. helper(new_vec, diff, candidates, i, res);
  22. }
  23. }
  24.  
  25. vector<vector<int>> combinationSum(vector<int>& candidates) {
  26. vector<vector<int>> res;
  27. helper(vector<int>(), 0, candidates, 0, &res);
  28. return res;
  29. }
  30. };
  31.  
  32. int main() {
  33. // your code goes here
  34. Solution s;
  35. vector<int> a {-5, 1, 10, 2, 3};
  36. vector<vector<int>> res= s.combinationSum(a);
  37. for (auto i: res)
  38. {
  39. for (auto j : i)
  40. cout << j <<endl;
  41. cout << "----" <<endl;
  42. }
  43. return 0;
  44. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
-5
-5
10
----
-5
2
3
----