Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
class Solution
{
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
vector<vector<int> > Result;
int Size = num.size();
if (Size < 4)
{
return Result;
}
// sort the array
sort(num.begin(), num.end());
for (int Index_first = 0; Index_first < (Size - 3); Index_first++)
{
int First = num[Index_first];
if ((Index_first != 0) && (num[Index_first - 1] == num[Index_first]))
{
continue;
}
for (int Index_second = Index_first + 1; Index_second < (Size - 2); Index_second++)
{
if ((Index_second != (Index_first + 1)) && (num[Index_second - 1] == num[Index_second]))
{
continue;
}
int Second = num[Index_second];
int Index_third = Index_second + 1;
int Index_foud = Size - 1;
while (Index_third < Index_foud)
{
int Third = num[Index_third];
int Fourd = num[Index_foud];
int Sum = First + Second + Third + Fourd;
if (Sum == target)
{
vector<int> Tmp;
Tmp.push_back(First);
Tmp.push_back(Second);
Tmp.push_back(Third);
Tmp.push_back(Fourd);
Result.push_back(Tmp);
Index_third++;
while ((Index_third <= (Size - 1)) && (num[Index_third] == num[Index_third - 1]))
{
Index_third++;
}
Index_foud--;
while ((Index_foud > Index_second) && (num[Index_foud] == num[Index_foud + 1]))
{
Index_foud--;
}
}
if (Sum < target)
{
Index_third++;
while ((Index_third < Size) && (num[Index_third] == num[Index_third - 1]))
{
Index_third++;
}
}
if (Sum > target)
{
Index_foud--;
while ((Index_foud > Index_second) && (num[Index_foud] == num[Index_foud + 1]))
{
Index_foud--;
}
}
}
}
}
return Result;
}
};原文:http://blog.csdn.net/sheng_ai/article/details/44586909