您的位置:首页 > 其它

18. 4Sum

2018-01-11 09:43 176 查看
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]
]

class Solution {
public:
void Sum4_helper_helper(vector<int> &nums,int begin,int end,int target,int first,int second,vector<vector<int>> &result)
{
int low=begin,high=end;

while(low<high)
{
if(high-low+1==2)
{
if(nums[low]+nums[high]==target)
{
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(second);
tmp.push_back(nums[low]);
tmp.push_back(nums[high]);
result.push_back(tmp);
}
return;
}
if(nums[low]+nums[high]>target) high--;
else if(nums[low]+nums[high]<target) low++;
else
{
if((low<end)&&(nums[low]==nums[low+1]))
{
low++;
continue;
}
if (high>begin&&(nums[high]==nums[high-1]))
{
high--;
continue;
}
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(second);
tmp.push_back(nums[low]);
tmp.push_back(nums[high]);
result.push_back(tmp);
low++;
}
}
}

void Sum4_helper(vector<int> &nums,int begin,int end,int target,int first,vector<vector<int>> &result)
{
for (int i=begin; i<=end;){
int t=target-nums[i];
Sum4_helper_helper(nums, i+1, end, t,first,nums[i],result);
int tmp=nums[i];
while(tmp==nums[i]) i++;
}
}

vector<vector<int>> fourSum(vector<int> &nums,int target)
{
vector<vector<int>> result;
if(nums.size()<4) return result;
sort(nums.begin(),nums.end());
for (int i=0; i<nums.size()-3;) {
int t=target-nums[i];
Sum4_helper(nums, i+1, nums.size()-1, t,nums[i],result);
int tmp=nums[i];
while(tmp==nums[i]&&i<nums.size()-3) i++;
}
return result;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 4sum