###### 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)

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
vector<int> four;
sort(nums.begin(),nums.end());
int i,j,k,t;
int sum=0;
int n=nums.size();
for(i=0;i<n;i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;

for(j=i+1;j<n;j++)
{
if(j>i+1&&nums[j]==nums[j-1])
continue;
k=j+1;
t=n-1;
while(k<t)
{
if(k>j+1&&nums[k]==nums[k-1])
{
k++;
continue;
}
// if(t<n-1&&nums[t]==nums[t+1])
// {
//  t--;
//  continue;
//  }
sum=nums[i]+nums[j]+nums[k]+nums[t];
if(sum==target)
{
four.push_back(nums[i]);
four.push_back(nums[j]);
four.push_back(nums[k]);
four.push_back(nums[t]);
result.push_back(four);
four.clear();
k++;
}
if(sum<target)
{
k++;
}
if(sum>target)
{
t--;
}
}
}

}
return result;
}
};

#### LeetCode 之 4Sum 的四种实现

2015-08-24 13:15:33

#### 18. 4Sum Leetcode Python

2015-01-17 11:55:43

#### LeetCode 18 4Sum (C,C++,Java,Python)

2015-05-10 15:04:02

#### [C++]LeetCode: 71 4Sum && kSum总结

2015-01-06 10:43:37

#### 4Sum -- LeetCode

2014-05-01 04:13:26

#### (Java)LeetCode-18. 4Sum

2016-05-30 19:59:46

#### [LeetCode] 018. 4Sum (Medium) (C++/Java/Python)

2015-03-04 17:57:45

#### Leetcode: 4Sum

2013-10-08 12:51:59

#### LeetCode 454 4Sum II 题解

2017-03-12 19:33:58

#### 18.4Sum

2015-04-04 09:53:55

4Sum