题目描述
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.
样例
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
Sort + DP $O(n^2)$
C++ 代码
// sort by (w, h)
// f[i]: 以 第i个envelope结尾的最长序列
// f[i] = 1 + max{ f[j] where j<i 且 可嵌套 }
int maxEnvelopes(vector<vector<int>>& xs) {
int n = xs.size();
if(n<=1) return n;
vector<int> f(n, 1);
f[0] = 1;
sort(begin(xs), end(xs),
[](const vector<int>&a, const vector<int>& b) { return a[0]<b[0] || (a[0]==b[0] && a[1]<b[1]); });
int res = 1;
for(int i=1; i<n; i++) {
for(int j=i-1; j>=0; j--) {
if(xs[i][0] > xs[j][0] && xs[i][1] > xs[j][1]) f[i] = max(f[i], 1+f[j]);
}
res = max(res, f[i]);
}
return res;
}
算法2
sort + binary search $O(nlogn)$
参考文献
C++ 代码
int maxEnvelopes(vector<vector<int>>& xs) {
sort(begin(xs), end(xs), [](const vector<int>& a, const vector<int>& b) {
return a[0]<b[0] || (a[0]==b[0]&&a[1]>b[1]);
});
vector<int> dp;
for(int i=0; i<xs.size(); i++) {
auto it = lower_bound(begin(dp), end(dp), xs[i][1]);
if(it == dp.end()) dp.push_back(xs[i][1]);
else *it = xs[i][1];
}
return dp.size();
}
lambda的仿函数很巧妙。棒!