leetcode第18题四数之和 https://leetcode.cn/problems/4sum/description/ Solution已通过测试 为方便测试 我自己写了个main 奇怪的是 返回却是空的 非常感谢解答 源代码如下
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
int n = nums.size();
if (n < 4) return ans;
if ((long)nums[0] + nums[1] + nums[2] + nums[3] > target) return ans;
if ((long)nums[n - 1] + nums[n - 2] + nums[n - 3] + nums[n - 4] < target) return ans;
for (int a = 0; a < n - 3; a++) {
if (a > 0 && nums[a] == nums[a - 1]) continue;
for (int b = a + 1; b < n - 2; b++) {
if (b > a + 1 && nums[b] == nums[b - 1]) continue;
int c = b + 1, d = n - 1;
while (c < d) {
long sum = (long)nums[a] + nums[b] + nums[c] + nums[d];
if (sum == target) {
ans.push_back({ nums[a] ,nums[b] , nums[c] , nums[d] });
while (c < d && nums[c] == nums[c + 1]) c++;
while (c < d && nums[d] == nums[d - 1]) d--;
c++;
d--;
} else if (sum < target) {
while (c < d && nums[c] == nums[c + 1]) c++;
c++;
} else {
while (c < d && nums[d] == nums[d - 1]) d--;
d--;
}
}
}
}
return ans;
}
};
int main() {
Solution solution;
vector<int> a = {0,0,0,1000000000,1000000000,1000000000};
int target = 1000000000;
auto ans = solution.fourSum(a, target);
for (auto x : ans) {
for (auto y : x) {
cout << y << " ";
}
cout << endl;
}
return 0;
}