您的位置:首页 > 运维架构

354. Russian Doll Envelopes

2016-06-10 23:57 239 查看
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]).

Analysis:

相当于二维的最长上升子序列,先将信封按第一维升序排列(注意第一维相同时,按第二维降序排列以免造成相同宽度的信封重复统计),然后找第二维的最大上升子序列

Source Code(C++):

#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Myless{
public:
bool operator()(pair<int, int>& p1, pair<int, int>& p2 ){
if (p1.first == p2.first) {
return p1.second>p2.second;
}
else {
return p1.first<p2.first;
}
}
};

class Solution {
public:
int maxEnvelopes(vector<pair<int, int> >& envelopes) {
if (envelopes.empty()) {
return 0;
}
sort(envelopes.begin(), envelopes.end(), Myless());
vector<int> maxLen(envelopes.size(), 1);
for (int i=1; i<envelopes.size(); i++)  //每次求以第i个数为终点的最长上升子序列的长度
{
for(int j=0; j<i; j++) {  //查看以第j个数为终点的最长上升子序列
if (envelopes[i].second > envelopes[j].second) {
maxLen[i] = max(maxLen[i], maxLen[j]+1);
}
}
}
return *max_element(maxLen.begin(), maxLen.end());
}
};

int main(){
Solution sol;
vector<pair<int, int> > v;
v.push_back(pair<int, int>(5, 4));
v.push_back(pair<int, int>(6, 4));
v.push_back(pair<int, int>(6, 7));
v.push_back(pair<int, int>(2, 3));
cout << sol.maxEnvelopes(v) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: