题目描述:
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:
static bool comp(const vector<int>& a, const vector<int>& b)
{
// 先按宽度从小到大排序,宽度相同时按照高度从大到小排序
// 因为宽度相同时不能重叠,将高度较大的放在前面避免这种情况
if(a[0]<b[0]) return true;
else if(a[0]==b[0]&&a[1]>b[1]) return true;
else return false;
}
int maxEnvelopes(vector<vector<int>>& envelopes) {
sort(envelopes.begin(),envelopes.end(),comp);
vector<int> dp;
for(vector<int>& envelope:envelopes)
{
auto it=lower_bound(dp.begin(),dp.end(),envelope[1]);
if(it==dp.end()) dp.push_back(envelope[1]);
else *it=envelope[1];
}
return dp.size();
}
};
本文探讨了俄罗斯套娃信封问题,这是一个经典的计算机科学问题,涉及到如何将多个具有不同宽度和高度的信封按照一定规则进行嵌套,以达到最大数量的嵌套。文章通过一个具体的例子解释了问题,并提供了一种解决方案,使用了排序和动态规划的思想。
521

被折叠的 条评论
为什么被折叠?



