- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathsum_of_subset.cpp
82 lines (68 loc) · 1.75 KB
/
sum_of_subset.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// This is also the solution for leetcode combination sum 2 Link - https://leetcode.com/problems/combination-sum-ii/
// Sum of subsets using Backtracking
#include<bits/stdc++.h>
usingnamespacestd;
voidfindCombination(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;
}
if (arr[ind] <= target)
{
ds.push_back(arr[ind]);
findCombination(ind + 1, target - arr[ind], arr, ans, ds);
ds.pop_back();
}
findCombination(ind + 1, target, arr, ans, ds);
}
voidprint(vector<vector<int>> &ans, int target)
{
cout << "The Subsets with Sum = " << target << " are : \n";
for (int i = 0; i < ans.size(); i++)
{
for (int j = 0; j < ans[i].size(); j++)
{
cout << ans[i][j] << "\t";
}
cout << "\n";
}
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
int ind;
vector<vector<int>> ans;
vector<int> ds;
findCombination(ind, target, candidates, ans, ds);
print(ans, target);
return ans;
}
intmain(int argc, charconst *argv[])
{
vector<int> candidates;
// {5, 10, 12, 13, 15, 18}
int n;
int target;
cout << "Enter the number of candidates: ";
cin >> n;
cout<<"Enter the target: ";
cin >> target;
cout << "Enter the candidates: ";
for(int i=0;i<n;i++)
{
int candidate;
cin >> candidate;
candidates.push_back(candidate);
}
combinationSum(candidates, target);
return0;
}
// Time Complexity :
// O((2^n)*k*logn)
// Space Complexity :
// Hypothetical // Depends on the subset output
// Generally k*n