-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0018.4sum.cpp
40 lines (34 loc) · 1.1 KB
/
#0018.4sum.cpp
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
34
35
36
37
38
39
40
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
if (target > 0 && target > 4 * nums.back()) {
return {};
}
if (target < 0 && target < 4 * nums.front()) {
return {};
}
int size = nums.size();
unordered_map<int, int> index;
for (int i = 0; i < size; ++i) {
index[nums[i]] = i;
}
set<vector<int>> v;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
for (int k = j + 1; k < size; k++) {
int t = target - nums[i] - nums[j] - nums[k];
if (t < nums[k]) {
break;
}
auto it = index.find(t);
if (it == index.end() || it->second <= k) {
continue;
}
v.insert({nums[i], nums[j], nums[k], t});
}
}
}
return vector<vector<int>>(begin(v), end(v));
}
};