Russian Doll Envelopes
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)
Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]]
, the maximum number of envelopes you can Russian doll is 3
([2,3] => [5,4] => [6,7]).
leetcode题目链接
思路:三次稳定的排序之后,得到两个不同的数组,一个是以长为序,一个是以宽为序,并长相同的部分,宽是有序的,宽相同地方长是有序的,然后两次o(n)遍历出来结果,但是这样是错误的
bool static compare(pair<int, int> a, pair<int, int> b)
{
if (a.first > b.first)
return true;
else if (a.first == b.first)
if (a.second > b.second)
return true;
return false;
}
bool static compare2(pair<int, int> a, pair<int, int> b)
{
if (a.second > b.second)
return true;
else if (a.second == b.second)
if (a.first > b.first)
return true;
return false;
}
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
int res2 = 1,res=1;
if (envelopes.empty()) return 0;
stable_sort(envelopes.begin(),envelopes.end(), compare);
pair<int, int> pre = envelopes[0];
for (int i = 1; i < envelopes.size(); i++)
if (pre.first > envelopes[i].first && pre.second > envelopes[i].second)
{
pre = envelopes[i];
res++;
}
stable_sort(envelopes.begin(), envelopes.end(), compare2);
pre = envelopes[0];
for (int i = 1; i < envelopes.size(); i++)
if (pre.first > envelopes[i].first && pre.second > envelopes[i].second)
{
pre = envelopes[i];
res2++;
}
return max(res, res2);
}
思路2:
将题目转化为求DAG图的最长路径,使用动态规划算法
参考博客