描述
Given an array S of n integers, are there elementsa, b, c inS such thata+b+c = 0? Find all uniquetriplets in the array which gives the sum of zero.
Note:
• Elements in a triplet (a, b, c)must be in non-descending order. (ie,a ≤b ≤c)
• The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:
(-1, 0, 1)
Given an array S of n integers, are there elementsa, b, c inS such thata+b+c = 0? Find all uniquetriplets in the array which gives the sum of zero.
Note:
• Elements in a triplet (a, b, c)must be in non-descending order. (ie,a ≤b ≤c)
• The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class ThreeSum
{
private:
void Sort(int a[], int n);
vector<pair<int, int>> TwoSumIsValue(int a[], int begin, int end, int value);
public:
vector<vector<int>> ThreeSumIsValue(int a[], int n, int value);
};
void ThreeSum::Sort(int a[], int n)
{
for (int i = 0; i < n-1; i++)
{
int min =i;
for (int j=i; j < n; j++)
{
if (a[j] < a[min])
min = j;
}
if (min != i)
{
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
vector<pair<int, int>> ThreeSum::TwoSumIsValue(int a[], int begin, int end, int value)
{
vector<pair<int, int>> res;
res.clear();
if (begin >= end)
return res;
//
while (begin < end)
{
if (a[begin] + a[end] == value)
{
res.push_back(make_pair(begin, end));
begin++;
end--;
}
else if (a[begin] + a[end]<value)
{
begin++;
}
else
{
end--;
}
}
return res;
}
vector<vector<int>> ThreeSum::ThreeSumIsValue(int a[], int n, int value)
{
vector<vector<int>> res;
res.clear();
if (n <= 2)
return res;
//
Sort(a, n);
for (int i = 0; i < n - 2; i++)
{
int temp = value - a[i];
vector<pair<int, int>> res2 = TwoSumIsValue(a, i + 1, n-1, temp);
if (res2.size()>0)
{
for (int j = 0; j < res2.size(); j++)
{
vector<int> temp_res;
temp_res.push_back(a[i]);
temp_res.push_back(a[res2[j].first]);
temp_res.push_back(a[res2[j].second]);
res.push_back(temp_res);
}
}
}
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
int main()
{
const int n = 10;
int a[n] = { 3, 8, -14, -14, 4, 6, 1, 9, 5, 7 };
ThreeSum threesum;
int value = 0;
vector<vector<int>> res = threesum.ThreeSumIsValue(a, n, value);
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
}