leetcode 354

问题

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Note:
Rotation is not allowed.

Example:

1
2
3
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

分析

这道题与最长上升子数组有点类似,我们可以先将所有信封按照第一维进行升序排列,然后在第一维相同的情况下按照第二位进行降序排列。再在第二位上执行查找最长上升子序列的算法。重点是需要思考为什么第二维要按照降序进行排列,这样就可以避免对

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
sort(envelopes.begin(), envelopes.end(), [](
const vector<int> &a, const vector<int> &b){
return (a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]));
});

vector<int> ans;
for (vector<int> &e: envelopes) {
if (ans.size() == 0 || e[1] > ans.back()) {
ans.push_back(e[1]);
} else {
auto it = lower_bound(ans.begin(), ans.end(), e[1]);
if ( *it > e[1] ) {
*it = e[1];
}
}
}
return ans.size();
}
};