当前位置:网站首页>最长严格递增子序列
最长严格递增子序列
2022-06-11 18:01:00 【AlbertOS】
引入
给定一个数组arr,返回arr的最长严格递增子序列的长度
子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组。
示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
解题方法
使用动态规划的思想,用i遍历数组,然后用j遍历小于i的数据,如果i的数据大于j的数据而且dp[i]的长度小于dp[j]+1的长度,则记录下来;
其实知道解题的方法和递推公式,写起来就简单了,
D ( x ) = { m a x ( d p [ j ] + 1 , d p [ i ] ) , 0 < = j < i 且 a r r [ j ] < a r r [ i ] 1 , 0 < = j < i 且 a r r [ j ] > a r r [ i ] D(x) = \begin{cases} max(dp[j]+1,dp[i] ), & 0<=j<i且arr[j]<arr[i] \\ 1,& 0<=j<i且arr[j]>arr[i] \\ \end{cases} D(x)={ max(dp[j]+1,dp[i]),1,0<=j<i且arr[j]<arr[i]0<=j<i且arr[j]>arr[i]
java代码
class Solution {
public int lengthOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = 1;
int maxans = 1;
for (int i = 1; i < nums.length; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxans = Math.max(maxans, dp[i]);
}
return maxans;
}
}
复杂度分析
时间复杂度: O ( n 2 ) O(n^2) O(n2),其中 n 为数组 nums的长度。动态规划的状态数为 n,计算状态dp[i] 时,需要 O(n)的时间遍历 d p [ 0 … i − 1 ] d p [ 0 … i − 1 ] dp[0 \ldots i-1]dp[0…i−1] dp[0…i−1]dp[0…i−1]的所有状态,所以总时间复杂度为 O ( n 2 ) O(n^2) O(n2)
空间复杂度: O ( n ) O(n) O(n),需要额外使用长度为 n 的 dp 数组。
边栏推荐
猜你喜欢

Tle6288r is a 6-channel (150 MOhm) intelligent multi-channel switch using intelligent power technology - keshijin mall

Network Security Threat Intelligence System

How ZABBIX can customize MySQL monitoring items and trigger alarms

Ctfhub SQL Boolean blind annotation

Mysql8 installation, Navicat installation, sqli labs setup

安装mariadb 10.5.7(tar包安装)

Common shortcut keys for Hello go (x) and GoLand

网络安全威胁情报体系

任意用户密码重置的10种方式

SISO Decoder for Repetition(补充章节4)
随机推荐
SQL error injection 1
网络安全威胁情报体系
SQL statement when the query condition is blank, all data will be queried by default. If it is not blank, the query will be performed according to the condition
SISO Decoder for min-sum(补充章节2)
Sa-Token 单点登录 SSO模式二 URL重定向传播会话示例
Hello go (XIII). Go language common standard library III
Getting started with CTF
Tle6288r is a 6-channel (150 MOhm) intelligent multi-channel switch using intelligent power technology - keshijin mall
[MapReduce] a complete Mr program case teaches you how to package and run with idea
Common shortcut keys for Hello go (x) and GoLand
Comparison of mongoose in express, KOA and egg
How to learn and self-study
How ZABBIX can customize MySQL monitoring items and trigger alarms
Hello go (XV). Go language common standard library V
async导致函数结果出乎意料,改变原来代码的意图;await is only valid in async functions and the top level bodies of modules
【实用脚本】获取某个文件的行号,然后删除文件内容。
神经网络与深度学习-2- 机器学习简单示例-PyTorch
“LSTM之父”新作:一种新方法,迈向自我修正的神经网络
【先收藏,早晚用得到】49个Flink高频面试题系列(二)
【新手上路常见问答】关于项目管理