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的升级版,基本思路完全一样,只是在外围多加了一层循环,需要注意的是c++中,vector的size()函数返回的值是unsigned类型,因此不可以直接-3,需要做类型的转换,否则会报错:Runtime Error Message: reference binding to null pointer of type 'struct value_type'
具体代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
set<vector<int> > res;
int number = nums.size();
for(int i = 0; i < number - 3; ++i)
{
for(int j = i + 1; j < number - 2; ++j)
{
int l = j + 1, r = nums.size() - 1;
int tar = target - nums[i] - nums[j];
while(l < r)
{
if(nums[l] + nums[r] < tar)
l++;
else if(nums[l] + nums[r] > tar)
r--;
else
{
res.insert({nums[i],nums[j],nums[l], nums[r]});
l++; r--;
}
}
}
}
return vector<vector<int> >(res.begin(),res.end());
}
};