-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum.cpp
58 lines (46 loc) · 1.14 KB
/
3Sum.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
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
// Hashing
vector<vector<int>> threeSum(vector<int> &nums)
{
int n = nums.size();
set<vector<int>> uniqueTriplets;
for (int i = 0; i < n; i++)
{
int tar = -nums[i];
set<int> s;
for (int j = i + 1; j < n; j++)
{
int third = tar - nums[j];
if (s.find(third) != s.end())
{
vector<int> trip = {nums[i], nums[j], third};
sort(trip.begin(), trip.end());
uniqueTriplets.insert(trip);
}
s.insert(nums[j]);
}
}
vector<vector<int>> ans(uniqueTriplets.begin(), uniqueTriplets.end());
return ans;
}
int main()
{
vector<int> nums = {-1, 0, 1, 2, -1, 4};
vector<vector<int>> result = threeSum(nums);
for (const auto &triplet : result)
{
cout << "[";
for (size_t i = 0; i < triplet.size(); ++i)
{
cout << triplet[i];
if (i < triplet.size() - 1)
cout << ", ";
}
cout << "]" << endl;
}
return 0;
}