class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > ans;
vector<int> tmp;
sort(num.begin(),num.end());
int len = num.size();
int i=0;
int j=1;
int k=2;
int l=3;
while (i<len-3) {
if(i>0&&num[i]==num[i-1]) {i++;continue;};
j=i+1;
while(j<len-2) {
while(j>i+1&&num[j]==num[j-1]) {j++;continue;}
k=j+1; l=len-1;
while(k<l) {
while(k>j+1&&num[k]==num[k-1]) {k++;continue;}
while(l<len-1&&num[l]==num[l+1]) {l--;continue;}
int sum = num[i]+num[j]+num[k]+num[l];
if(k<l) {
if(sum==target) {
tmp.clear();
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(num[k]);
tmp.push_back(num[l]);
k++;
ans.push_back(tmp);
}
else if(sum>target) {l--;}
else {k++;}}
}
j++;
}
i++;
}
return ans;
}
};
4sum
最新推荐文章于 2017-04-26 01:21:50 发布