-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombinationalSum-1&2
89 lines (81 loc) · 2.09 KB
/
combinationalSum-1&2
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
83
84
85
86
87
88
89
#include<iostream>
#include<vector>
#include<algorithm>
void print(std::vector<int>p){
std::cout<<"("<<p[0];
for(int i=1;i<p.size();++i)
std::cout<<" "<<p[i];
std::cout<<")";
}
void print2(std::vector<std::vector<int>>res){
for(int i=0;i<res.size();++i){
std::vector<int>p = res[i];
std::cout<<"("<<p[0];
for(int i=1;i<p.size();++i)
std::cout<<" "<<p[i];
std::cout<<")";
}
}
void combinationalSum(int a[], int n,int sum,std::vector<int>&p,bool &flag,
std::vector<std::vector<int>>&res){
if(n<=0 || sum<0)
return;
if(sum==0){
flag=true;
std::vector<int>inter=p;
std::sort(inter.begin(),inter.end());
if(std::find(res.begin(),res.end(),inter)==res.end()){
res.push_back(inter);
}
return;
}
p.push_back(a[n-1]);
combinationalSum(a,n,sum-a[n-1],p,flag,res);
p.pop_back();
combinationalSum(a,n-1,sum,p,flag,res);
}
void combinationalSum2(int a[], int n,int sum,std::vector<int>&p,bool &flag,
std::vector<std::vector<int>>&res){
// static std::vector<std::vector<int>>res;
if(n<0 || sum<0)
return;
if(sum==0){
flag=true;
std::vector<int>inter=p;
std::sort(inter.begin(),inter.end());
if(std::find(res.begin(),res.end(),inter)==res.end()){
res.push_back(inter);
// print(inter);
}
return;
}
p.push_back(a[n-1]);
combinationalSum2(a,n-1,sum-a[n-1],p,flag,res);
p.pop_back();
combinationalSum2(a,n-1,sum,p,flag,res);
}
int main()
{
int T;
std::cin>>T;
while(T--){
int n,sum;
std::cin>>n;
int a[n];
for(int i=0;i<n;++i)
std::cin>>a[i];
std::cin>>sum;
bool flag=false;
std::vector<int>p;
static std::vector<std::vector<int>>res;
combinationalSum2(a,n,sum,p,flag,res);
if(flag==false)
std::cout<<"Empty";
else{
std::sort(res.begin(),res.end());
print2(res);
}
res.clear();
std::cout<<"\n";
}
}