梦第二次破碎,这道题不能用哈希。和三数之和一样,需要双指针方法,简单来说就是再三数之和外面再套一层循环,难就难在剪枝和去重,简直折磨,究极折磨。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>> ret;
for (int k = 0; k < nums.size(); ++k){
if (nums[k] > target && nums[k] >= 0) break;;
if (k > 0 && nums[k] == nums[k-1]) continue;
for (int i = k + 1; i < nums.size(); ++i){
if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) break;
if (i > k + 1 && nums[i] == nums[i-1]) continue;
int left = i + 1;
int right = nums.size() - 1;
while (right > left){
if ((long) nums[k] + nums[i] + nums[left] + nums[right] > target) --right;
else if ((long) nums[k] + nums[i] + nums[left] + nums[right] < target) ++left;
else {
ret.push_back(vector<int>{nums[k], nums[i], nums[left], nums[right]});
while (right > left && nums[left] == nums[left+1]) ++left;
while (right > left && nums[right] == nums[right-1]) --right;
++left;
--right;
}
}
}
}
return ret;
}
};