Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
  4.         if (candidates.empty()) return {};
  5.        
  6.         vector<int> curr;
  7.         vector<vector<int>> res;
  8.        
  9.         solveCombinationSum(candidates, 0, target, curr, res);
  10.        
  11.         return res;
  12.     }
  13. private:
  14.     void solveCombinationSum(const vector<int>& candidates, int pos, int target,
  15.                              vector<int>& curr, vector<vector<int>>& res) {
  16.         if (pos == candidates.size()) {
  17.             if (target == 0) res.push_back(curr);
  18.             return;
  19.         }
  20.        
  21.         // skip current number
  22.         solveCombinationSum(candidates, pos + 1, target, curr, res);
  23.        
  24.         // include curr number
  25.         for (int s = candidates[pos]; s <= target; s += candidates[pos]) {
  26.             curr.push_back(candidates[pos]);
  27.             solveCombinationSum(candidates, pos + 1, target - s, curr, res);
  28.         }
  29.        
  30.         while(!curr.empty() && curr.back() == candidates[pos])
  31.             curr.pop_back();
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement