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]
]
思路: 和求三个和类似, 先将数组排序, 然后固定一个值,求三个之和。
时间复杂度: O(n^3)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> Res;
std::sort(nums.begin(),nums.end());
if(nums.size() <4)
return Res;
for(int i = 0;i<nums.size();i++)
{
/* Only for the target is 0
if(nums[i]> target)
break;*/
for(int j = i+1;j< nums.size();j++)
{
int front = j+1;
int back = nums.size()-1;
int subTarget = target - nums[i]-nums[j];
while(front <back)
{
int sum = nums[front]+nums[back];
if(sum> subTarget)
{
back--;
}
else if(sum < subTarget)
{
front++;
}
else
{
vector<int> subRes;
subRes.push_back(nums[i]);
subRes.push_back(nums[j]);
subRes.push_back(nums[front]);
subRes.push_back(nums[back]);
Res.push_back(subRes);
while(front < back && nums[front] == subRes[2])
front++;
while(front <back && nums[back] == subRes[3])
back--;
}
}
while(j < nums.size()-1 && nums[j] == nums[j+1])
j++;
}
while(i< nums.size()-1 && nums[i] == nums[i+1])
i++;
}
return Res;
}
};