您的位置:首页 > 编程语言 > C语言/C++

4Sum

2016-07-14 19:32 477 查看
题目描述:

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]
]

解题思路:
类似于题目3Sum,不同之处是这里需要固定两个数字,3Sum的解题思路可以参考:3Sum

AC代码如下:

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int numlen = nums.size();
if (nums.size()<4) return res;

sort(nums.begin(), nums.end());
for (int i = 0; i < numlen; i++)
{
if (i != 0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
for (int j = i + 1; j < numlen; j++)
{
if (j != i + 1 && nums[j] == nums[j - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组
int begin = j + 1;
int end = numlen - 1;
while (begin < end)
{
int sum = nums[i] + nums[j] + nums[begin] + nums[end];
if (sum == target)
{
vector<int> tmp = {nums[i],nums[j],nums[begin],nums[end]};

res.push_back(tmp);
while (++begin<end && nums[begin] == nums[begin - 1]); //跳过重复的元素,避免结果中出现重复的四元组
while (--end>begin && nums[end] == nums[end + 1]); //跳过重复的元素,避免结果中出现重复的四元组

}
else if (sum<target)
begin++;
else
end--;
}
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 4Sum C++