题目: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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
给定一个数组,找出所有4个数的组合使得它们的和为target
思路:和3Sum,Two Sum都是类似的。主要是两个点:
1. 对数组排序,然后双指针分别从头尾遍历
2. 注意去重的问题
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int nsize = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> result;
for(int i = ; i < nsize; i++){
if(i != && nums[i] == nums[i - ])
continue;
for(int j = i + ; j < nsize; j++){
if(j != i + && nums[j] == nums[j - ])
continue;
int p = j + , q = nsize - ;
while(p < q){
int sum = nums[i] + nums[j] + nums[p] + nums[q];
if(sum < target){
++p;
continue;
}
if(sum > target){
--q;
continue;
} vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[p]);
tmp.push_back(nums[q]);
result.push_back(tmp); while(++p < q && nums[p] == nums[p - ]);
while(p < --q && nums[q] == nums[q + ]);
}
}
}
return result;
}
};