Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d =target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [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] ]
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > res;
vector<int> tempres;
if(nums.empty())
return res;
if(nums.size()<=3)
return res;
sort(nums.begin(), nums.end());
for(int j=0; j<nums.size()-3; j++)
{
if (j > 0 && nums[j] == nums[j - 1]) continue; //这一步很关键
for(int i=j+1; i<nums.size()-2; i++)
{
if(i>j+1 && nums[i] == nums[i - 1]) continue; //这一步也很关键
int start =i+1;
int end = nums.size()-1;
int sum = nums[i];
while(start<end)
{
if((nums[start]+nums[end]+nums[i]+nums[j])==target)
{
tempres.push_back(nums[j]);
tempres.push_back(nums[i]);
tempres.push_back(nums[start]);
tempres.push_back(nums[end]);
res.push_back(tempres);
while( start< end && nums[start] == nums[start + 1]) ++start;
while (start< end && nums[end] == nums[end - 1]) --end;
tempres.clear();
++start;
--end;
}else if((nums[start]+nums[end]+nums[i]+nums[j])>target)
{
--end;
}else
{
++start;
}
}
}
}
return res;
}
};