-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum.cpp
68 lines (52 loc) · 1.37 KB
/
CombinationSum.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <vector>
#include <set>
using namespace std;
set<vector<int>> s;
void getAllCombinations(vector<int> &arr, int idx, int target, vector<vector<int>> &ans, vector<int> &combin)
{
int n = arr.size();
if (idx == n || target < 0)
{
return;
}
if (target == 0) // base case
{
if (s.find(combin) == s.end())
{
ans.push_back(combin);
s.insert(combin);
}
return;
}
combin.push_back(arr[idx]);
getAllCombinations(arr, idx + 1, target - arr[idx], ans, combin); // single choice
getAllCombinations(arr, idx, target - arr[idx], ans, combin); // multiple choice
combin.pop_back(); // backtracking
getAllCombinations(arr, idx + 1, target, ans, combin); // exclusion choice
}
vector<vector<int>> combinationSum(vector<int> &arr, int target)
{
vector<vector<int>> ans;
vector<int> combin;
getAllCombinations(arr, 0, target, ans, combin);
return ans;
}
int main()
{
vector<int> arr = {2, 3, 5};
int target = 8;
vector<vector<int>> result = combinationSum(arr, target);
// Printing the subsets
cout << "Combinations are:\n";
for (const auto &combination : result)
{
cout << "{ ";
for (int num : combination)
{
cout << num << " ";
}
cout << "}\n";
}
return 0;
}