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] ]
和之前的题目一样,不过这次我用了set容器,防止出现重复,简单一点。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> res;
sort(nums.begin(),nums.end());
for(int i=0;i<int(nums.size()-3);i++)
{
for(int j=i+1;j<int(nums.size())-2;j++)
{
int l=j+1;
int r=nums.size()-1;
while(l<r)
{
int sum=nums[i]+nums[j]+nums[l]+nums[r];
if(sum==target)
{
vector<int> out;
out.push_back(nums[i]);
out.push_back(nums[j]);
out.push_back(nums[l]);
out.push_back(nums[r]);
res.insert(out);
l++;
r--;
}
else if(sum<target)
l++;
else
r--;
}
}
}
return vector<vector<int>> (res.begin(),res.end());
}
};
其中有一个问题是,在两个for循环时,如果不强制int转换的话,会超时。。。我也不是很懂为什么加上了就可以AC。。这个再研究研究~