一:题目
二:上码
class Solution {
public:vector<vector<int>> fourSum(vector<int>& nums, int target) {vector<vector<int> >ans;vector<int> v;sort(nums.begin(),nums.end());for(int i = 0; i < nums.size(); i++) {//去重 防止相邻的两个数相等if(i > 0 && nums[i] == nums[i-1]) {continue;}for(int j = i+1; j < nums.size(); j++) {//去重if(j > i+1 && nums[j] == nums[j-1]) {continue;} int left = j+1;int right = nums.size()-1;while(left < right){//nums[i]+nums[j]+nums[left]+nums[right] > target 执行出错if(nums[i]+nums[j] > target - (nums[left]+nums[right])) right--;else if(nums[i]+nums[j] < target -(nums[left]+nums[right])){left++;}else{v.push_back(nums[i]);v.push_back(nums[j]);v.push_back(nums[left]);v.push_back(nums[right]);ans.push_back(v);//去重处理while(left < right && nums[left] == nums[left+1]) left++;while(left < right && nums[right] == nums[right-1]) right--;//完成一组后left++;right--;v.clear();}}}}return ans;}
};
这个题跟三个数之和的解法一样就是多了一层for循环而已