-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtargetSumSubsetsRecursion.cpp
More file actions
64 lines (51 loc) · 1.34 KB
/
targetSumSubsetsRecursion.cpp
File metadata and controls
64 lines (51 loc) · 1.34 KB
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
// Question : https://youtu.be/zNxDJJW40_k?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
//Explanation : https://www.pepcoding.com/resources/online-java-foundation/recursion-backtracking/target_sum_subsets/topic
//Solution : https://youtu.be/HGDmj5NrrjM?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
//NOTE : Negative number may also be given in input (I have taken a bit further)
#include<iostream>
#include<vector>
using namespace std;
void targetSum(vector<int> &arr,int i,vector<vector<int> > &ans,vector<int> temp,int currentSum,int target)
{
if(i>arr.size())
{
return;
}
else if(i==arr.size())
{
if(currentSum==target)
{
ans.push_back(temp);
}
}
else
{
//we have 2 choices , either to include the current number or not include
//Not-Include
targetSum(arr,i+1,ans,temp,currentSum,target);
//include
temp.push_back(arr[i]);
targetSum(arr,i+1,ans,temp,currentSum+arr[i],target);
}
}
int main()
{
int n;
cin>>n;
vector<int> arr(n,0);
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int target;
cin>>target;
vector<vector<int> > ans;
vector<int> temp;
targetSum(arr,0,ans,temp,0,target);
for(auto &v:ans)
{
for(auto &nums:v)
cout<<nums<<" ";
cout<<"\n";
}
}