-
Notifications
You must be signed in to change notification settings - Fork 1
/
combination_sum.cpp
70 lines (63 loc) · 1.15 KB
/
combination_sum.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
#include <bits/stdc++.h>
using namespace std;
void print(vector <int> q)
{cout<<"(";
for(int i=0;i<q.size()-1;i++)
cout<<q[i]<<" ";
cout<<q[q.size()-1]<<")";
}
void sum(vector <int> v,vector <int> q,int k,int s,int j,bool &r)
{
if(s==k)
{ r=true;
print(q);
return;
}
for(int i=j;i<v.size();i++)
{
if(s>k)
return;
q.push_back(v[i]);
sum(v,q,k,s+v[i],j,r);
j++;
if(q.size()==0)
return;
q.pop_back();
}
}
int main() {
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector <int> v;
set<int> w;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
w.insert(x);
}
set <int> ::iterator it=w.begin();
while(it!=w.end())
{
v.push_back(*it);
it++;
}
int k;
cin>>k;
vector <int> q;
sort(v.begin(),v.end());
int s=0;
int j=0;
bool r=false;
sum(v,q,k,s,j,r);
if(!r)
cout<<"Empty";
cout<<endl;
}
return 0;
}