题目:
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:
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]).
代码:
方法一——超时的:
class Solution {
public:
bool doll(vector<int>& a,vector<int>& b){
return a[0]<b[0]&&a[1]<b[1];
}
int maxEnvelopes(vector<vector<int>>& envelopes) {
int len=envelopes.size();
if(len<=0)return 0;
map<vector<int>,int>m;
sort(envelopes.begin(),envelopes.end());
m[envelopes[0]]=0;
int record=0;
for(int i=1;i<len;i++){
for(int j=i-1;j>=0;j--){
if(doll(envelopes[j],envelopes[i])){
m[envelopes[i]]=max(m[envelopes[i]],m[envelopes[j]]+1);
record=max(record,m[envelopes[i]]);
}
}
}
return record+1;
}
};
方法二——思路和上一个相同,但是dp数组是坐标形式,就会快不少。:
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int res = 0, n = envelopes.size();
vector<int> dp(n, 1);
sort(envelopes.begin(), envelopes.end());
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (envelopes[i][0] > envelopes[j][0] && 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) {
vector<int> dp;
sort(envelopes.begin(), envelopes.end(), [](const vector<int>&a, const vector<int>&b){
if (a[0] == b[0]) return a[1] > b[1];
return a[0] < b[0];
});
for (int i = 0; i < envelopes.size(); ++i) {
int left = 0, right = dp.size(), t= envelopes[i][1];
while (left < right) {
int mid = left + (right - left) / 2;
if (dp[mid] < t) left = mid + 1;
else right = mid;
}
if (right >= dp.size()) dp.push_back(t);
else dp[right] = t;
}
return dp.size();
}
};