陪伴而非守候
vector> fourSum(vector& nums, int target)
{
int n = nums.size();
QuickSort(nums,0,n-1); int i,j,k,s,sum,t1,t2;
vector<int> turple;
vector<vector<int>> result;
if(n < 4)
return result;
t1 = nums[0];
for(i=0;i<n-3;i++)
{
if(i && t1 == nums[i])
continue;
t2 = nums[i+1];
for(j=i+1;j<n-2;j++)
{
if(t2 == nums[j] && j >i+1)
continue;
sum = target - nums[i] - nums[j];
k = j+1;
s = n-1;
while(k<s)
{
if(nums[k] + nums[s] == sum)
{
turple.push_back(nums[i]);
turple.push_back(nums[j]);
turple.push_back(nums[k]);
turple.push_back(nums[s]);
result.push_back(turple);
turple.clear();
k++;
s--;
}
else if(nums[k] + nums[s] < sum)
k++;
else
s--;
}
t2 = nums[j];
}
t1 = nums[i];
}
result.erase(unique(result.begin(),result.end()),result.end());
return result;
}
void QuickSort(vector<int>&nums,int low,int high)
{
if(low<high)
{
int pivot = nums[low];
int first = low;
int last = high;
while(first<last)
{
while(nums[last] > pivot && last > first)
{
--last;
}
nums[first] = nums[last];
while(nums[first] <= pivot && last >first)
{
++first;
}
nums[last] = nums[first];
}
nums[first] = pivot;
QuickSort(nums,low,first-1);
QuickSort(nums,first+1,high);
}
else
return;
}