-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallFourSumNumbers.cpp
98 lines (85 loc) · 2.5 KB
/
allFourSumNumbers.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
// arr[] : int input array of integers
// k : the quadruple sum required
/*void fourSumUtil(vector<int> &arr, int k, int ind, vector<int> &temp, set<vector<int>> &ans) {
if (temp.size() == 4) {
int sum = 0;
for (auto ele : temp) sum += ele;
if (sum == k) ans.insert(temp);
return;
}
if (ind == arr.size()) return;
fourSumUtil(arr, k, ind + 1, temp, ans);
temp.push_back(arr[ind]);
fourSumUtil(arr, k, ind + 1, temp, ans);
temp.pop_back();
}
vector<vector<int>> fourSum(vector<int> &arr, int k) {
vector<vector<int>> ans;
set<vector<int>> tempAns;
vector<int> temp;
sort(arr.begin(), arr.end());
fourSumUtil(arr, k, 0, temp, tempAns);
for (auto ele : tempAns) ans.push_back(ele);
return ans;
}*/
vector<vector<int>> fourSum(vector<int> &arr, int k) {
int n = arr.size(), start, end;
sort(arr.begin(), arr.end());
set<vector<int>> ans;
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
start = j + 1;
end = n - 1;
while (start < end) {
if (arr[i] + arr[j] + arr[start] + arr[end] == k) {
ans.insert({arr[i], arr[j], arr[start], arr[end]});
start++;
end--;
} else if (arr[i] + arr[j] + arr[start] + arr[end] < k) {
start++;
} else {
end--;
}
}
}
}
vector<vector<int>> result;
for (auto ele : ans) {
result.push_back(ele);
}
return result;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, k, i;
cin >> n >> k;
vector<int> a(n);
for (i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
vector<vector<int> > ans = ob.fourSum(a, k);
for (auto &v : ans) {
for (int &u : v) {
cout << u << " ";
}
cout << "$";
}
if (ans.empty()) {
cout << -1;
}
cout << "\n";
}
return 0;
} // } Driver Code Ends