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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
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) {
int len = num.size();
int i,j,k,m,s1=INT_MAX,s2=INT_MAX,s3=INT_MAX,s4=INT_MAX;
vector<int> a;
vector<vector<int> > aa;
sort(num.begin(), num.end());
a.clear();
aa.clear();
for(i=0; i<len; ++i)
{
while(num[i] == s1)
{
++i;
}
s2 = INT_MAX;
for(j=i+1; j<len; ++j)
{
while(num[j] == s2)
{
++j;
}
s3 = INT_MAX;
s4 = INT_MAX;
for(k=j+1,m=len-1; k<m; )
{
while(k < m && s3 == num[k])
{
++k;
}
while(k < m && s4 == num[m])
{
--m;
}
if (k == m)
{
break;
}
a.clear();
if (num[i]+num[j]+num[k]+num[m] < target)
{
++k;
}
else if(num[i]+num[j]+num[k]+num[m] > target)
{
--m;
}
else
{
//cout << "i " << i <<" j " << j << " k " << k<<" m " << m << endl;
a.push_back(num[i]);
a.push_back(num[j]);
a.push_back(num[k]);
a.push_back(num[m]);
aa.push_back(a);
s3 = num[k];
s4 = num[m];
++k, --m;
}
}
s2 = num[j];
}
s1 = num[i];
}
return aa;
}
};