vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > ret;
if(num.size()<4)
return ret;
sort(num.begin(),num.end());
for(int i=0;i<num.size()-3;i++){
if(i>0&&num[i]==num[i-1]) continue;
for(int j=i+1;j<num.size()-2;j++){
if(j>i+1&&num[j]==num[j-1]) continue;
int l=j+1,r=num.size()-1;
while(l<r){
int sum=num[i]+num[j]+num[l]+num[r];
if(sum>target)
r--;
else if(sum<target)
l++;
else{
vector<int> tmp;
tmp.push_back(num[i]);tmp.push_back(num[j]);tmp.push_back(num[l]);tmp.push_back(num[r]);
ret.push_back(tmp);
do{l++;}while(l<r&&num[l]==num[l-1]);
do{r--;}while(l<r&&num[r]==num[r+1]);
}
}
}
}
return ret;
}
No comments:
Post a Comment