-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.cpp
More file actions
46 lines (46 loc) · 1.07 KB
/
3Sum.cpp
File metadata and controls
46 lines (46 loc) · 1.07 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
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> findTriplets(vector<int>&arr, int n){
sort(arr.begin(),arr.end());
vector<vector<int>> ans;
set<vector<int>> unique;
for(int i=0;i<n;i++){
int j=i+1;
int k=n-1;
while(j<k){
if((arr[i]+arr[j]+arr[k])==0){
unique.insert({arr[i],arr[j],arr[k]});
j++;
k--;
}
else if((arr[i]+arr[j]+arr[k])<0){
j++;
}
else if((arr[i]+arr[j]+arr[k])>0){
k--;
}
}
}
for(auto triplets: unique){
ans.push_back(triplets);
}
return ans;
}
int main(){
int n;
cout<<"Enter Size of array : ";
cin>>n;
vector<int> arr;
cout<<"Enter elements of array : ";
int a;
for(int i=0;i<n;i++){
cin>>a;
arr.push_back(a);
}
cout<<"Triplets having sum 0 are : "<<'\n';
vector<vector<int>> ans=findTriplets(arr, n);
for(int i=0; i<n; i++){
cout<<ans[i]<<"";
}
return 0;
}