Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
[5,4], [6, 4], [6, 7], [2, 3] => [2, 3], [5, 4], [6, 7], [6, 4]
求 3474 的最大升序子序列长度,即 347,长度为 3
dp[i]
表示以 envelopes[i][1]
结尾的最长子序列长度class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (empty(envelopes)) {
return 0;
}
sort(begin(envelopes), end(envelopes),
[](auto& x, auto& y) { return tie(x[0], y[1]) < tie(y[0], x[1]); });
vector<int> dp(size(envelopes), 1);
int res = 1;
for (int i = 0; i < size(dp); ++i) {
for (int j = 0; j < i; ++j) {
if (envelopes[i][1] > envelopes[j][1]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
res = max(res, dp[i]);
}
return res;
}
};
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (empty(envelopes)) {
return 0;
}
sort(begin(envelopes), end(envelopes),
[](auto& x, auto& y) { return tie(x[0], y[1]) < tie(y[0], x[1]); });
vector<int> v{envelopes[0][1]};
for (int i = 1; i < size(envelopes); ++i) {
if (envelopes[i][1] > v.back()) {
v.emplace_back(envelopes[i][1]);
} else {
*lower_bound(begin(v), end(v), envelopes[i][1]) = envelopes[i][1];
}
}
return size(v);
}
};