4Sum
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)
与3Sum类似,只是我们现在需要遍历两个元素,a,b,然后在利用两个指针的方法求c,d
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) { int n=num.size();
int i,j,k,l;
int a,b,c,d;
sort(num.begin(),num.end());
vector<vector<int> > result;
for(int i=;i<n-;i++)
{
for(int j=i+;j<n-;j++)
{
k=j+;
l=n-; while(k<l)
{
a=num[i];
if(i>&&num[i]==num[i-])
{
break;
} b=num[j];
if(j>i+&&num[j]==num[j-])
{
break;
} c=num[k];
if(k>j+&&num[k]==num[k-])
{
k++;
continue;
} d=num[l];
if(l<n-&&num[l]==num[l+])
{
l--;
continue;
} int sum=a+b+c+d; if(sum<target)
{
k++;
}
else if(sum>target)
{
l--;
}
else
{
vector<int> tmp();
tmp[]=a;
tmp[]=b;
tmp[]=c;
tmp[]=d;
result.push_back(tmp);
k++;
l--;
}
}
}
}
return result;
}
};