问题:
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的变体,我是在那道题的基础上做的。也是采用了最简单粗暴的遍历,选出一个数a,然后求剩下三个数的和为target-a,这就变成了3Sum问题了。下面是代码:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
sort(nums.begin(),nums.end());
for(int i = 0 ; i < nums.size() ; ++i ){
if( i > 0 && nums[i] == nums[i-1] ){
continue;
}
int target2 = target - nums[i];
for( int j = i+1 ; j < nums.size() ; j++ ){
if( j > i + 1 && nums[j] == nums[j-1] ){
continue;
}
int k = j + 1 , x = nums.size() - 1;
while( k < x ){
if( nums[j] + nums[k] + nums[x] == target2 ){
res.push_back({nums[i],nums[j],nums[k],nums[x]});
while( k < x && nums[k+1] == nums[k] ) { k++; }
while( k < x && nums[x-1] == nums[x] ) { x--; }
k++;
x--;
}else if( nums[j] + nums[k] + nums[x] < target2 ){
k++;
}else {
x--;
}
}
}
}
return res;
}
};