Problem
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
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.
Return the maximum number of envelopes can you Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Constraints:
- 1 <= envelopes.length <= 5000
- envelopes[i].length == 2
- 1 <= wi, hi <= 104
Example1
Input: envelopes = [[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]).
Example2
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
Solution
二维LIS。
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& w) {
int n = w.size();
sort(w.begin(), w.end());
vector<int> f(n);
int res = 0;
for (int i = 0; i < n; i ++ ) {
f[i] = 1;
for (int j = 0; j < i; j ++ )
if (w[j][0] < w[i][0] && w[j][1] < w[i][1])
f[i] = max(f[i], f[j] + 1);
res = max(res, f[i]);
}
return res;
}
};