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: 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一样
代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > result;
sort(nums.begin(),nums.end());
int len = nums.size();
for(int i = 0;i<len-3;i++)
{
for(int j = i+1;j<len-2;j++)
{
int other = target-nums[i]-nums[j];
int front=j+1,back=len-1;
while(front<back)
{
int sum = nums[front]+nums[back];
if(sum > other)
{
back--;
}
else if(sum < other)
{
front++;
}
else
{
vector<int> tmp(4,0);
tmp[0] = nums[i];
tmp[1] = nums[j];
tmp[2] = nums[front];
tmp[3] = nums[back];
result.push_back(tmp);
while(front < back && nums[front] == tmp[2])
front++;
while(front < back && nums[back] == tmp[3])
back--;
}
}
while(j<len-2 && nums[j+1] == nums[j])
j++;
}
while(i < len-3 && nums[i+1] == nums[i])
i++;
}
return result;
}
};
思路二:通过对思路一的代码进行分析,发现其实存在很多情况不需要进行后续的比较操作,比如当数列的前四个数的和大于target时,完全就不需要进行后续的比较操作了;当数列的前两个数和最后两个数的和小于target,那么在锁定前两个数的情况下该数列不可能存在四个数的和为target。通过对这些多余情况的剪枝,代码的效率得到了不小的提升。(该情况适用于之前类似的3Sum等问题)
代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > result;
sort(nums.begin(),nums.end());
int len = nums.size();
for(int i = 0;i<len-3;i++)
{
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break;
if(nums[i]+nums[len-3]+nums[len-2]+nums[len-1] < target) continue;
for(int j = i+1;j<len-2;j++)
{
if(nums[i]+nums[j]+nums[j+1]+nums[j+2] > target) break;
if(nums[i]+nums[j]+nums[len-2]+nums[len-1] < target) continue;
int other = target-nums[i]-nums[j];
int front=j+1,back=len-1;
while(front<back)
{
int sum = nums[front]+nums[back];
if(sum > other)
{
back--;
}
else if(sum < other)
{
front++;
}
else
{
vector<int> tmp(4,0);
tmp[0] = nums[i];
tmp[1] = nums[j];
tmp[2] = nums[front];
tmp[3] = nums[back];
result.push_back(tmp);
while(front < back && nums[front] == tmp[2])
front++;
while(front < back && nums[back] == tmp[3])
back--;
}
}
while(j<len-2 && nums[j+1] == nums[j])
j++;
}
while(i < len-3 && nums[i+1] == nums[i])
i++;
}
return result;
}
};