题目
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问题,n^3
代码:
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int>> ans;
int size=num.size();
if(size<4)
return ans;
sort(num.begin(),num.end());
long long sum;
vector<int> qua;
int i=0,j=1,k=2,l=size-1;
while(k<l)
{
while(k<l) //3SUM
{
while(k<l) //2SUM
{
sum=num[i]+num[j]+num[k]+num[l];
if(sum==target)
{
qua.clear();
qua.push_back(num[i]);
qua.push_back(num[j]);
qua.push_back(num[k]);
qua.push_back(num[l]);
ans.push_back(qua);
k++;
while(k<l&&num[k]==num[k-1])
k++;
l--;
while(k<l&&num[l]==num[l+1])
l--;
}
else if(sum<target)
k++;
else
l--;
}
j++;
while(j<size&&num[j]==num[j-1])
j++;
k=j+1;
l=size-1;
}
i++;
while(i<size&&num[i]==num[i-1])
i++;
j=i+1;
k=i+2;
l=size-1;
}
return ans;
}
};