思路:
思路和三数之和一样。
代码:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(),nums.end());
vector<vector<int>> res;
for(int i = 0; i < n; i++){
if(i && nums[i] == nums[i - 1]) continue;
for(int j = i + 1; j < n; j++){
if(j > i+ 1 && nums[j] == nums[j - 1]) continue;
for(int u = j + 1,k = n - 1; u < k; u++){
if(u > j+1 && nums [u] == nums[u-1]) continue;
while(u < k - 1 && nums[i] + nums[j] >= target - nums[u] - nums[k - 1]) k--;
if(nums[i] + nums[j] == target - nums[u] - nums[k]){
res.push_back({nums[i], nums[j], nums[u], nums[k]});
}
}
}
}
return res;
}
};
评论区