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
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Example:
Given envelopes =
Analysis:
相当于二维的最长上升子序列,先将信封按第一维升序排列(注意第一维相同时,按第二维降序排列以免造成相同宽度的信封重复统计),然后找第二维的最大上升子序列。
Source Code(C++):
(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; }
相关文章推荐
- centos安装软件的两种命令rpm,yum
- ListView(1)控件架构与ArrayAdapter详解
- nginx使用keepalived实现高可用
- 上下文&flags特性参数&复杂ListView(多种布局)&获取应用名的拼音(首字母拼音滑动改变)&PopupWindow
- rp-pppoe in openwrt
- openSUSE vsftpd 搭建
- CentOS7 修改网卡名称为eth0 & 在VMWare中添加多网卡配置
- elementary os 软件及一些问题
- Linux 文件目录
- linux命令 - export - 设置环境变量
- u-boot与linux内核间的参数传递过程分析
- LVS+Keepalived高可用环境部署梳理(主主和主从模式)
- linux下配置mysql默认编码utf8
- hadoop & hive任务优化之系统概况及任务详情查看方法
- linux密码破解
- OpenStack Liberty 高可用性概述和参考-第一部分
- NFS服务器配置
- Caused by: org.xml.sax.SAXParseException; systemId: file:/opt/apache-nutch-2.2.1/runtime/local/conf/
- solrCloud+tomcat+zookeeper配置(一)
- (二)Linux基础之系统结构目录与正则表达式