标签:
链接:https://leetcode.com/problems/4sum/
问题描述:
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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
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)
Hide Tags Array Hash Table Two Pointers
Hide Similar Problems (M) Two Sum (M) 3Sum
这一题和3sum类似,思想也是从3sum中借鉴过来的http://blog.csdn.net/efergrehbtrj/article/details/46855331。需要注意的是,这一题返回的结果需要去除重复的。c++容器set可以用来很好的解决这个问题。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
int p1,p2;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
p1=j+1;
p2=nums.size()-1;
while(p1<p2)
{
if(nums[i]+nums[j]+nums[p1]+nums[p2]==target)
{
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[j]);
temp.push_back(nums[p1]);
temp.push_back(nums[p2]);
result.push_back(temp);
p1++;
p2--;
}
else if(nums[i]+nums[j]+nums[p1]+nums[p2]<target)
p1++;
else
p2--;
}
}
}
set<vector<int>> si(result.begin(),result.end());
vector<vector<int>> res(si.begin(),si.end());
return res;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46855353