# 4Sum

174人阅读 评论(0)

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;
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56080次
• 积分：3120
• 等级：
• 排名：第11433名
• 原创：255篇
• 转载：1篇
• 译文：0篇
• 评论：1条
阅读排行
最新评论