Leetcode: 18. 4Sum
Description
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.
Example
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]
]
思路
- 跟15,16题思路差不多一致
- 最主要的是考虑到重复的情况
代码
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int len = nums.size();
if(len < 4) return res;
int i = 0, j = 0, s = 0, e = 0, sum = 0;
sort(nums.begin(), nums.end());
for(i = 0; i < len; ++i){
if(i > 0 && nums[i] == nums[i - 1]) continue;
for(j = i + 1; j < len; ++j){
if(j > i + 1 && nums[j] == nums[j - 1]) continue;
s = j + 1;
e = len - 1;
while(s < e){
if(s > j + 1 && nums[s] == nums[s - 1]){
s++;
continue;
}
if(e < len - 1 && nums[e] == nums[e + 1]){
e--;
continue;
}
sum = nums[i] + nums[j] + nums[s] + nums[e];
if(sum > target) e--;
else if(sum < target) s++;
else{
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[s]);
tmp.push_back(nums[e]);
res.push_back(tmp);
s++;
}
}
}
}
return res;
}
};