MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / Solution

Class Solution

C++/combination-sum.cpp:2–30  ·  view source on GitHub ↗

Solved using backtracking

Source from the content-addressed store, hash-verified

1// Solved using backtracking
2class Solution {
3public:
4 void recur(vector<vector<int>>& ans, vector<int>& v, vector<int>& candidates, int target, int curr){
5 if(target==0){
6 ans.push_back(v);
7 }
8 if(target<0){
9 return;
10 }
11 for(int i = curr; i< candidates.size(); i++){
12 if(candidates[i]<=target){
13 v.push_back(candidates[i]);
14 recur(ans,v,candidates,target-candidates[i],i);
15 v.pop_back();
16 }
17 }
18 }
19
20 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
21 vector<vector<int>>ans;
22 vector<int> v;
23
24 sort(candidates.begin(), candidates.end());
25
26 recur(ans,v,candidates,target,0);
27
28 return ans;
29 }
30};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected