1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); vector <vector<int>> res; for(int i = 0; i + 3 < nums.size(); ++i) { if(i > 0 && nums[i] == nums[i-1]) continue; for(int j = i+1; j + 2 < nums.size(); ++j) { if(j > i+1 && nums[j] == nums[j-1]) continue; int ttarget = target - nums[i] - nums[j] ; int l = j+1, r = nums.size()-1; while(l < r) { int sum = nums[l] + nums[r]; if(ttarget == sum) { res.push_back({nums[i],nums[j],nums[l],nums[r]}); l++; r--; while(l < r && nums[l] == nums[l-1]) l++; while(l < r && nums[r] == nums[r+1]) r--; } if(ttarget > sum) l++; if(ttarget < sum) r--; } } } return res; } };
|