-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy path4sum.java
123 lines (53 loc) · 1.58 KB
/
4sum.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
Class Solution {
public:
vector<vector<int>> fourSum(vector<int>& v, int t) {
return kSum(v, t, 4);
}
vector<vector<int>> kSum(vector<int>& v, int t, int k) {
const int n = v.size();
if (n < k)
return {};
sort(v.begin(), v.end());
vector<int> prefix_ids;
for (int i = 0; i < k - 2; i++)
prefix_ids.push_back(i);
set<vector<int>> tuples;
do
{
vector<int> prefix_v;
long long prefix_sum = 0;
for (int i : prefix_ids) {
prefix_sum += v[i];
prefix_v.push_back(v[i]);
}
for (int l = prefix_ids.back() + 1, r = n - 1; l < r; l++, r--) {
const long long sum = prefix_sum + v[l] + v[r];
if (sum < t)
r++;
else if (sum > t)
l--;
else {
vector<int> suffix_v = {v[l], v[r]};
vector<int> tuple;
tuple.insert(tuple.end(), prefix_v.begin(), prefix_v.end());
tuple.insert(tuple.end(), suffix_v.begin(), suffix_v.end());
tuples.emplace(tuple);
}
}
} while (next_combination(prefix_ids, n - k + 1));
return vector(tuples.begin(), tuples.end());
}
bool next_combination(vector<int>& v, int m) {
const int n = v.size();
int i = n - 1;
int j = m;
while (i >= 0 && v[i] >= j) {
i--;
j--;
}
if (i < 0)
return false;
for (v[i++]++; i < n; i++)
v[i] = v[i - 1] + 1;
return true;
}