https://leetcode-cn.com/problems/4sum/
思路:固定前2个数字 + 双指针
vector<vector<int> > fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int> > res;
if (nums.size() < 4) {
return res;
}
for (int i = 0; i < nums.size() - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.size() - 2; j++) {
int start = j + 1, end = nums.size() - 1;
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
//cout << nums[i] << " " << nums[j] << " " << nums[start] << " " << nums[end] << endl;
while(end > start) {
int value = nums[i] + nums[j] + nums[start] + nums[end];
if (value < target) {
start += 1;
} else if (value > target) {
end -= 1;
} else {
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[j]);
temp.push_back(nums[start]);
temp.push_back(nums[end]);
res.push_back(temp);
while(end > 0 && nums[end] == nums[end - 1]) end -= 1;
while(start < nums.size() - 1 && nums[start] == nums[start + 1]) start += 1;
end -= 1;
}
}
}
}
return res;
}