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还是不一样的,难点在于不能重复的四个元素。 所以最好的办法是首尾不重复,所以前两个循环从头尾开始。 然后中间跳跃的时候要考虑special case, 就是跳index得时候至少要先算一次。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector <int> > ct;
int size=num.size();
if (size<4)
return ct;
sort(num.begin(),num.end());
for (int i=0; i<size-3;i++){
if ( i>0 && num[i]==num[i-1] )
continue;
for (int j=size-1;j>i;j--){
if (j<size-1 && num[j]==num[j+1])
continue;
int beg=i+1;
int end=j-1;
while(beg<end){
if (beg>i+1 && num[beg]==num[beg-1]){
beg++;
continue;
}
if (end<j-1 && num[end]==num[end+1]){
end--;
continue;
}
if (beg>=end)
break;
int res=num[i]+num[j]+num[beg]+num[end]-target;
if (res==0) {
vector<int> tmp={num[i], num[beg], num[end],num[j]};
ct.push_back(tmp);
beg++;
end--;
} else if (res<0)
beg++;
else
end--;
}
}
}
return ct;
}
};
int main()
{
Solution s;
vector<int> test={1,0,-1,0,-2,2};
vector< vector<int> > res=s.fourSum(test,0);
for (int i=0;i<res.size(); i++){
for (int j=0; j<res[i].size(); j++){
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}