当前位置:网站首页>646.最长数对链(动态规划)
646.最长数对链(动态规划)
2022-07-30 05:38:00 【Linke66】


解题思路:
动态规划(最长升序子序列变体)
dp[i]表示到索引为i的这个元素为止,有多少个满足要求的数对,即第一个元素大于前一个元素的第二个元素。
动态转移方程
if(pairs[i][0]>pairs[j][1]){
dp[i]=max(dp[i],dp[j]+1);
但是由于给的数组是无序的,因此需要首先对数组作处理。
首先数组按照第二个元素的升序排列,而不是按第一个元素的升序排列,原因是前者能够为后面留下更多的空间。
sort(pairs.begin(),pairs.end(),
[](const vector<int>& a,const vector<int>& b)
{
return a[1]<b[1];
});
完整代码如下
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
int n=pairs.size();
if(n==1) return 1;
sort(pairs.begin(),pairs.end(),
[](const vector<int>& a,const vector<int>& b)
{
return a[1]<b[1];
});
vector<int> dp(n,1);
int max_len=0;
for(int i=0;i<n;++i){
for(int j=0;j<i;++j){
if(pairs[i][0]>pairs[j][1]){
dp[i]=max(dp[i],dp[j]+1);
}
max_len=max(max_len,dp[i]);
}
}
return max_len;
}
};
边栏推荐
- cnpm installation steps
- SOA(面向服务架构)是什么?
- net start mysql MySQL 服务正在启动 . MySQL 服务无法启动。 服务没有报告任何错误。
- Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
- k折交叉验证(k-fold Cross-validation)
- 【Koltin Flow(一)】五种创建flow的方式
- Teach you to completely uninstall MySQL
- 【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
- np.argsort()函数详细解析
- 安装Nuxt.js时出现错误:TypeError:Cannot read property ‘eslint‘ of undefined
猜你喜欢

每日练习------输出一个整数的二进制数、八进制数、十六进制数。

MySQL 有这一篇就够(呕心狂敲37k字,只为博君一点赞!!!)

MySQL 用户授权

应用实践 | Apache Doris 在百度智能云计费账单系统的应用实践

PyCharm使用教程(较详细,图+文)

分布式事务之 LCN框架的原理和使用(二)

图形镜像对称(示意图)

Navicat connection MySQL error: 1045 - Access denied for user 'root'@'localhost' (using password YES)

MySQL (2)

How is crawler data collected and organized?
随机推荐
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
torch.optim.Adam()
cmd(命令行)操作或连接mysql数据库,以及创建数据库与表
It's time to have to learn English, give yourself multiple paths
解决phpstudy无法启动MySQL服务
CISP-PTE Zhenti Demonstration
MySQL的 DDL和DML和DQL的基本语法
子查询作为检索表时的不同使用场景以及是否需要添加别名的问题
MySQL (2)
Mysql8.+学习笔记
MySQL fuzzy query performance optimization
G Bus Count (Google Kickstart2014 Round D Problem B) (DAY 89)
4461. Range Partition (Google Kickstart2022 Round C Problem B)
"Hou Lang" programmer version, a speech dedicated to a new generation of programmers, He Bing's "Hou Lang" speech imitation show
Machine Learning - Gradient Descent Optimization - C language implementation
mysql time field is set to current time by default
SOA(面向服务架构)是什么?
Difference between cookie and session
MySQL模糊查询性能优化
4461. 范围分区(Google Kickstart2022 Round C Problem B)