一、 问题描述
Leecode第十八题,题目为:
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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]
]
问题理解为:
给定一个包含n个整数的数组和一个整数目标,nums中是否有a、b、c和d元素使得a + b + c + d = target?找出数组中四数之和为给定目标和的所有唯一组。
注意:
解集不能重复。
例:
给定数组nums = [1,0, - 1,0, - 2,2], target = 0。
解为:
[
[- 1, 0, 0, 1],
[-2, -1, 1, 2],
[- 2, 0, 0, 2]
]
二、算法思路
1、
2、
三、实现代码
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > res;
if(nums.empty()) return res;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++)
{
int target_three = target - nums[i];
for(int j = i + 1; j < nums.size(); j++)
{
int target_two = target_three - nums[j];
int front = j + 1;
int back = nums.size() - 1;
while(front < back)
{
int two_sum = nums[front] + nums[back];
if(two_sum < target_two) front++;
else if(two_sum > target_two) back--;
else
{
vector<int> quadruplet(4, 0);
quadruplet[0] = nums[i];
quadruplet[1] = nums[j];
quadruplet[2] = nums[front];
quadruplet[3] = nums[back];
res.push_back(quadruplet);
while(front < back && nums[front] == quadruplet[2]) front++;
}
}
while(j + 1 < nums.size() && nums[j + 1] == nums[j]) j++;
}
while(i + 1 < nums.size() && nums[i + 1] == nums[i]) i++;
}
return res;
}
};