leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0040.cpp (766B)


      1 class Solution {
      2     vector<vector<int>> res;
      3     vector<int> crnt;
      4 
      5     void rec(vector<int> &candidates, int target, int sum, int start = 0) {
      6         if (sum == target)
      7             res.push_back(crnt);
      8         else if (sum < target) {
      9             for (int i = start; i < candidates.size(); i++) {
     10                 if (i != start && candidates[i] == candidates[i - 1]) continue;
     11                 crnt.push_back(candidates[i]);
     12                 rec(candidates, target, sum + candidates[i], i + 1);
     13                 crnt.pop_back();
     14             }
     15         }
     16     }
     17 
     18   public:
     19     vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
     20         sort(candidates.begin(), candidates.end());
     21         rec(candidates, target, 0);
     22         return res;
     23     }
     24 };