Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
class Solution
{
public:
vector<vector<int> > threeSum(vector<int> &num)
{
int Size = num.size();
vector<vector<int> > Result;
if (Size < 3)
{
return Result;
}
sort(num.begin(), num.end());
for (int Index_outter = 0; Index_outter < (Size - 2); Index_outter++)
{
int First = num[Index_outter];
int Second = num[Index_outter + 1];
const int Target = 0;
if ((Index_outter != 0) && (First == num[Index_outter - 1]))
{
continue;
}
int Start = Index_outter + 1;
int End = Size - 1;
while (Start < End)
{
Second = num[Start];
int Third = num[End];
int Sum = First + Second + Third;
if (Sum == Target)
{
vector<int> Tmp;
Tmp.push_back(First);
Tmp.push_back(Second);
Tmp.push_back(Third);
Result.push_back(Tmp);
Start++;
End--;
while (num[Start] == num[Start - 1])
{
Start++;
}
while (num[End] == num[End + 1])
{
End--;
}
}
if (Sum < Target)
{
Start++;
while (num[Start] == num[Start -1])
{
Start++;
}
}
if (Sum > Target)
{
End--;
if (num[End] == num[End + 1])
{
End--;
}
}
}
}
return Result;
}
};
原文地址:http://blog.csdn.net/sheng_ai/article/details/44317707