Approach
Sorting and greedy selection
For 4Sum, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 51 lines of C++ from the credited upstream file 18.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> fourSum(vector<int>& nums, int target) {4 vector<vector<int>> ans;5 vector<int> path;6 ranges::sort(nums);7 nSum(nums, 4, target, 0, nums.size() - 1, path, ans);8 return ans;9 }10 11 private:12 13 void nSum(const vector<int>& nums, long n, long target, int l, int r,14 vector<int>& path, vector<vector<int>>& ans) {15 if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)16 return;17 if (n == 2) {18 19 while (l < r) {20 const int sum = nums[l] + nums[r];21 if (sum == target) {22 path.push_back(nums[l]);23 path.push_back(nums[r]);24 ans.push_back(path);25 path.pop_back();26 path.pop_back();27 ++l;28 --r;29 while (l < r && nums[l] == nums[l - 1])30 ++l;31 while (l < r && nums[r] == nums[r + 1])32 --r;33 } else if (sum < target) {34 ++l;35 } else {36 --r;37 }38 }39 return;40 }41 42 for (int i = l; i <= r; ++i) {43 if (i > l && nums[i] == nums[i - 1])44 continue;45 path.push_back(nums[i]);46 nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);47 path.pop_back();48 }49 }50};51