-
Notifications
You must be signed in to change notification settings - Fork 17
/
comsum1.cpp
43 lines (39 loc) · 1.1 KB
/
comsum1.cpp
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
34
35
36
37
38
39
40
41
42
43
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void findCombination(int ind, int target, vector < int > & arr, vector < vector < int >> & ans, vector < int > & ds) {
if (ind == arr.size()) {
if (target == 0) {
ans.push_back(ds);
}
return;
}
// pick up the element
if (arr[ind] <= target) {
ds.push_back(arr[ind]);
findCombination(ind, target - arr[ind], arr, ans, ds);
ds.pop_back();
}
findCombination(ind + 1, target, arr, ans, ds);
}
public:
vector < vector < int >> combinationSum(vector < int > & candidates, int target) {
vector < vector < int >> ans;
vector < int > ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
};
int main() {
Solution obj;
vector < int > v {2,3,6,7};
int target = 7;
vector < vector < int >> ans = obj.combinationSum(v, target);
cout << "Combinations are: " << endl;
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++)
cout << ans[i][j] << " ";
cout << endl;
}
}