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] ]
Subscribe to see which companies asked this question
#include "common.h"
using namespace std;
/*
leetcode 18. 4Sum
时间复杂度: N^3
该题如果用暴力搜索,四重循环,时间复杂度是N^4,这样很可能
会超时,所以考虑先排序所有的元素,然后对四个变量也按照一定
的前后顺序排列,有方向的搜索解(四个元素的和比较target来确定
搜索方向)
这里要考虑去重,每一个循环里都要考虑
*/
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > record;
record.clear();
if(nums.size()<4) return record;
vector<int> temp;
int a=0,b=0,c=0,d=0;
sort(nums.begin(),nums.end());
for(a=0;a<nums.size()-3;a++)
{
if(nums[a]+nums[a+1]+nums[a+2]+nums[a+3]>target) break;//剪枝操作
if(a!=0 && nums[a]==nums[a-1]) //去重操作
continue;
for(d=nums.size()-1;d>2;d--)
{
if(nums[d]+nums[d-1]+nums[d-2]+nums[d-3]<target) break;//剪枝操作,效果很明显
if(d!=(nums.size()-1) && nums[d]==nums[d+1]) //去重操作
continue;
b=a+1;
c=d-1;
while(b<c)
{
//去重操作
if(nums[b]==nums[b-1] && (b-1)!=a)
{
b++;
continue;
}
if(nums[c]==nums[c+1] && (c+1)!=d)
{
c--;
continue;
}
if(target==(nums[a]+nums[b]+nums[c]+nums[d]))
{
temp.clear();
temp.push_back(nums[a]);
temp.push_back(nums[b]);
temp.push_back(nums[c]);
temp.push_back(nums[d]);
record.push_back(temp);
b++;
}
else if(target<(nums[a]+nums[b]+nums[c]+nums[d]))
c--;
else
b++;
}
}
}
return record;
}
};
int main() {
int a[]={5,5,3,5,1,-5,1,-2};
vector<int> nums(a,a+sizeof(a)/sizeof(int));
for(int i=0;i<nums.size();i++)
cout<<nums[i]<<" ";
cout<<endl;
int target=4;
Solution s;
vector<vector<int> > ve;
ve=s.fourSum(nums,target);
for(int i=0;i<ve.size();i++)
{
cout<<endl;
for(int j=0;j<ve[i].size();j++)
cout<<ve[i][j]<<" ";
}
getchar();
return 0;
}