Skip to content

Commit 30be43c

Browse files
authored
Backtracking solution for combinational Sum
1 parent cabb853 commit 30be43c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void findNumbers(vector<int>& ar, int sum, vector<vector<int> >& res, vector<int>& r, int i) {
5+
if (sum == 0) {
6+
res.push_back(r);
7+
return;
8+
}
9+
while (i < ar.size() && sum - ar[i] >= 0) {
10+
11+
r.push_back(ar[i]);
12+
findNumbers(ar, sum - ar[i], res, r, i);
13+
i++;
14+
r.pop_back();
15+
}
16+
}
17+
18+
vector<vector<int> > combinationSum(vector<int>& ar, int sum) {
19+
sort(ar.begin(), ar.end());
20+
ar.erase(unique(ar.begin(), ar.end()), ar.end());
21+
22+
vector<int> r;
23+
vector<vector<int> > res;
24+
findNumbers(ar, sum, res, r, 0);
25+
26+
return res;
27+
}
28+
29+
int main() {
30+
31+
int n, sum;
32+
cout << "Enter the size of array: ";
33+
cin >> n;
34+
35+
vector<int> ar(n, 0);
36+
37+
cout << "Enter the elements of the array: ";
38+
for (auto& i : ar) {
39+
cin >> i;
40+
}
41+
42+
cout << "Enter the required sum: ";
43+
cin >> sum;
44+
45+
vector<vector<int> > res = combinationSum(ar, sum);
46+
47+
if (res.size() == 0) {
48+
cout << "Empty";
49+
return 0;
50+
}
51+
for (int i = 0; i < res.size(); i++) {
52+
if (res[i].size() > 0) {
53+
cout << "[";
54+
for (int j = 0; j < res[i].size(); j++){
55+
cout << res[i][j];
56+
if (j<(res[i].size()-1))
57+
cout << ", ";
58+
}
59+
cout << "]\n";
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)