|
| 1 | +/* |
| 2 | +4Sum |
| 3 | +==== |
| 4 | +
|
| 5 | +Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: |
| 6 | +
|
| 7 | +0 <= a, b, c, d < n |
| 8 | +a, b, c, and d are distinct. |
| 9 | +nums[a] + nums[b] + nums[c] + nums[d] == target |
| 10 | +You may return the answer in any order. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: nums = [1,0,-1,0,-2,2], target = 0 |
| 14 | +Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: nums = [2,2,2,2,2], target = 8 |
| 18 | +Output: [[2,2,2,2]] |
| 19 | +
|
| 20 | +Constraints: |
| 21 | +1 <= nums.length <= 200 |
| 22 | +-109 <= nums[i] <= 109 |
| 23 | +-109 <= target <= 109 |
| 24 | +*/ |
| 25 | + |
| 26 | +class Solution |
| 27 | +{ |
| 28 | +public: |
| 29 | + vector<vector<int>> fourSum(vector<int> &nums, int target) |
| 30 | + { |
| 31 | + int n = nums.size(); |
| 32 | + sort(nums.begin(), nums.end()); |
| 33 | + vector<vector<int>> ans; |
| 34 | + |
| 35 | + for (int i = 0; i < n - 3; ++i) |
| 36 | + { |
| 37 | + for (int j = i + 1; j < n - 2; ++j) |
| 38 | + { |
| 39 | + int tar = target - nums[j] - nums[i]; |
| 40 | + |
| 41 | + int k = j + 1, l = n - 1; |
| 42 | + while (k < l) |
| 43 | + { |
| 44 | + if (nums[k] + nums[l] == tar) |
| 45 | + { |
| 46 | + ans.push_back({nums[i], nums[j], nums[k], nums[l]}); |
| 47 | + while (k < l && nums[k] == nums[k + 1]) |
| 48 | + k++; |
| 49 | + while (k < l && nums[l] == nums[l - 1]) |
| 50 | + l--; |
| 51 | + k++; |
| 52 | + l--; |
| 53 | + } |
| 54 | + else if (nums[k] + nums[l] < tar) |
| 55 | + k++; |
| 56 | + else |
| 57 | + l--; |
| 58 | + } |
| 59 | + while (j < n - 2 && nums[j] == nums[j + 1]) |
| 60 | + j++; |
| 61 | + } |
| 62 | + while (i < n - 3 && nums[i] == nums[i + 1]) |
| 63 | + i++; |
| 64 | + } |
| 65 | + return ans; |
| 66 | + } |
| 67 | +}; |
0 commit comments