思路:
设置 i j k n 四个游标,思想如同三数之和
# include<iostream>
# include<vector>
# include<string>
# include<algorithm>
# include<math.h>
# include<climits>
using namespace std;
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int i=0, j, k, n;
int size = nums.size();
vector<vector<int>>res;
sort(nums.begin(), nums.end());//将nums有序化
while (i < size - 3) {//i的活动范围
j = i + 1;
while (j < size - 2) {//j的活动范围
k = j + 1;
n = size - 1;
while (k < n) {
if ((nums[i] + nums[j] + nums[k] + nums[n]) > target) {
n--;
while (k < n && nums[n] == nums[n + 1])n--;
}
else if ((nums[i] + nums[j] + nums[k] + nums[n]) < target) {
k++;
while (k < n && nums[k] == nums[k - 1])k++;
}
else {//与target一致
res.push_back({ nums[i] , nums[j] , nums[k] , nums[n] });//将此数组入vector
k++;
while (k < n && nums[k] == nums[k - 1])k++;
n--;
while (k < n && nums[n] == nums[n + 1])n--;
}
}//k<n的循环
j++;
while (j < size - 2 && nums[j] == nums[j - 1])j++;
}
i++;
while (i < size - 3 && nums[i] == nums[i - 1])i++;
}
return res;
}
int main(void) {
vector<int> nums;
nums.push_back(-3);
nums.push_back(-2);
nums.push_back(-1);
nums.push_back(0);
nums.push_back(0);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector<vector<int>>res;
res = fourSum(nums, 0);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}