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一样,两点法,没什么好说的。
有很多人想了很多判断条件去优化程序效率,我觉得没什么必要,于是直接在15的代码上改了。
附上前两道3Sum的地址,会做以后这题就肯定没问题了!
https://cloud.tencent.com/developer/article/1019316
https://cloud.tencent.com/developer/article/1019317
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>> result;
int len=(nums.size()-3);
for(int i=0;i<len;i++)
{
if(i!=0 && nums[i]==nums[i-1])continue;
for(int j=i+1;j<(len+1);j++)
{
if(j!=i+1 && nums[j]==nums[j-1])continue;
int l=j+1,r=nums.size()-1;
while(l<r)
{
int com=nums[i]+nums[j]+nums[l]+nums[r];
if(com>target)
r--;
else if(com<target)
l++;
else
{
result.push_back({nums[i], nums[j], nums[l], nums[r]});
while(l<r && nums[l]==nums[l+1]) l++;
while(l<r && nums[r]==nums[r-1]) r--;
r--;
l++;
}
}
}
}
return result;
}
};