双指针+排序
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
if(nums.size() < 4) {
return ans;
}
for(int i = 0; i < nums.size(); i++){
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
for(int j = i + 1; j < nums.size(); j++){
if(j > i + 1 && nums[j] == nums[j - 1]){
continue;
}
int l = j + 1, r = nums.size() - 1;
while(l < r){
int res = nums[i] + nums[j] + nums[l] + nums[r];
if(res == target){
vector t = {nums[i], nums[j], nums[l], nums[r]};
ans.push_back(t);
while(l < r && nums[l] == nums[++l]);
while(l < r && nums[r] == nums[--r]);
}else if(res > target){
r--;
}else if(res < target){
l++;
}
}
}
}
return ans;
}
};
题目链接:https://leetcode-cn.com/problems/4sum/submissions/