-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39. Combination Sum.cpp
More file actions
33 lines (28 loc) · 875 Bytes
/
39. Combination Sum.cpp
File metadata and controls
33 lines (28 loc) · 875 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
Problem Link: https://leetcode.com/problems/combination-sum/
Time: 5 ms (Beats 78.8%), Space: 10.8 MB (Beats 81.75%)
*/
class Solution {
private:
void findComb(int idx, int target, vector<int> &arr, vector<vector<int>> &ans, vector<int> &v){
if(idx == arr.size()){
if(target == 0){
ans.push_back(v);
}
return;
}
if(arr[idx] <= target){
v.push_back(arr[idx]);
findComb(idx, target - arr[idx], arr, ans, v);
v.pop_back(); // imp cond
}
findComb(idx+1, target, arr, ans, v); // idx+1
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> v;
findComb(0, target, candidates, ans, v);
return ans;
}
};