forked from dsnehasish74/Hacktoberfest21_Algo_Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriplets.cpp
56 lines (47 loc) · 1.15 KB
/
triplets.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
#include <bits/stdc++.h>
using namespace std;
// Function to efficiently find out three elements whose sum is equal to a given sum
// Time complexity : O(n2)
vector< vector<int> > triplets(vector <int> arr, int Sum)
{
vector < vector<int> > res;
int n = arr.size();
for (int i = 0; i <= n-3; ++i)
{
int j = i+1;
int k = n-1;
while(j < k)
{
int currsum = arr[i] + arr[j] + arr[k];
if(currsum == Sum){
res.push_back({arr[i] , arr[j] , arr[k]});
j++;
k--;
}
else if(currsum > Sum)
k--;
else
j++;
}
}
return res;
}
int main()
{
// Example
vector <int> v = {1,2,3,4,5,6,7,8,9,15};
int Sum = 32;
auto p = triplets(v,Sum);
if(p.size()==0)
cout << "No pair found" ;
else
{
for (auto triplet : p)
{
// Outputting all valid triplet sets
for(auto ans : triplet)
cout << ans << " ";
cout << endl;
}
}
}