354. 俄罗斯套娃信封问题
给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
说明:
不允许旋转信封。
示例:
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
排序+dp O(N^2)
class Solution {
private:
vector<int> dp;
static bool cmp(vector<int> a, vector<int> b){
if(a[0]!=b[0]) return a[0]<b[0];
return a[1]<b[1];
}
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int n= envelopes.size();
sort(envelopes.begin(),envelopes.end(),cmp);
dp.resize(n,1); //以i结尾的信封,可以套多少
int res=0;
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中设定cmp函数,需要设为static函数;
因为cmp函数中无this对象!
二分+最长上升子序列
将信封按高度升序排,再按宽度降序排列;
寻找宽度的最长上升子序列,即为最长的套娃数量;
cmp+二分
class Solution {
private:
vector<int> dp;
static bool cmp(vector<int>& a, vector<int>& b){
if(a[0]!=b[0]) return a[0]<b[0];
return a[1]>b[1];
}
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int n= envelopes.size();
sort(envelopes.begin(),envelopes.end(),cmp);
dp.resize(n,1); //以i结尾的信封,可以套多少
int end=0;
for(auto t:envelopes){
int left=0;
int right=end;
while(left<right){
int mid=left+(right-left)/2;
if(dp[mid]<t[1]) left=mid+1;
else right=mid;
}
dp[left]=t[1];
if(left==end) end++;
}
return end;
}
};
lower_bound+sort
class Solution {
private:
vector<int> dp;
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int n= envelopes.size();
sort(envelopes.begin(),envelopes.end(),[](vector<int>& a, vector<int>& b){if(a[0]!=b[0]) return a[0]<b[0];return a[1]>b[1];});
for(auto t:envelopes){
auto iter=lower_bound(dp.begin(),dp.end(),t[1]);
if(iter==dp.end()) dp.push_back(t[1]);
else dp[iter-dp.begin()]=t[1];
}
return dp.size();
}
};
注意点
排序传引用&,时间快几倍