问题描述
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]
]
解法思路
初始想法是扩展3Sum,对前两个数进行遍历,后两个数用while遍历,但最后显示超时。经过进一步研究发现,去除一些不可能的情形后,可以通过
C++代码
vector<vector<int > > ans;
if(nums.size()<=3)return ans;
int n = nums.size();
sort(nums.begin(),nums.end());
for(int i=0;i<n-3;i++)
{
//删去不可能的情况
if(i>0 && nums[i-1]==nums[i])continue;
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)break;
if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target)continue;
for(int j=i+1;j<n-2;j++)
{
//删去不可能的情况
if(j>i+1 && nums[j-1]==nums[j])continue;
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)break;
if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target)continue;
int l = j+1;
int r = n-1;
while(l<r)
{
int s = nums[i]+nums[l]+nums[r]+nums[j];
if(s==target)
{
ans.push_back({nums[i],nums[j],nums[l],nums[r]});
do
{
l++;
}while(l<r && nums[l]==nums[l-1]);
do
{
r--;
}while(l<r && nums[r+1]==nums[r]);
}
else if(s<target)l++;
else r--;
}
}
}
return ans;
计算结果
Runtime: 16 ms, faster than 93.26% of C++ online submissions for 4Sum.
Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for 4Sum.