300. Longest Increasing Subsequence
Problem
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.Your algorithm should run in O( n2 n 2 ) complexity.
Follow up: Could you improve it to O( nlogn n l o g n ) time complexity?
题目
给定一个无序的整数数组,求最长递增子序列的长度。
例如:
给定数组 [10, 9, 2, 5, 3, 7, 101, 18],最长递增子序列是 [2, 3, 7, 101],因此,长度为4。注意,最长递增子序列的组合可能不止一种,但只需要求出长度即可。算法的复杂度应该不高于O( n2 n 2 ) 。
延伸: 算法时间复杂度能够改进为 O( nlogn n l o g n )?
算法发杂度为O( n2 n 2 ) 的方法
思路
对于长度为N的数组
A[N]={a0,a1,a2,⋯,an−1}
A
[
N
]
=
{
a
0
,
a
1
,
a
2
,
⋯
,
a
n
−
1
}
,假设我们想求以
aj
a
j
结尾的最大递增子序列长度,设为
L(i)
L
(
i
)
,则:
即以 ai a i 结尾的最长递增子序列长度为以 {a0,a1,a2,⋯,ai−1} { a 0 , a 1 , a 2 , ⋯ , a i − 1 } 中小于 ai a i 的数 aj a j 结尾的最长子序列长度加1的最大值。若 ai a i 小于 {a0,a1,a2,⋯,ai−1} { a 0 , a 1 , a 2 , ⋯ , a i − 1 } 中的所有数,则以 ai a i 结尾的最长递增子序列长度为1。
算法步骤
假设A为给定的长度为N的数组,L为与数组大小相等的数组。
1. 初始化L的值均为1.
2. i取1到N-1,j取0到i-1,若A[i] > A[j]且L[i] < L[j]+1,则L[i] = L[j]+1。
3. 数组L中的最大值即为数组A的最长递增子序列长度。
代码(C++)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int size = nums.size();
if(size == 0) return 0;
vector<int> length(size,1);
for(int i = 1;i<size;i++){
for(int j = 0;j<i;j++){
if(nums[i] > nums[j] && length[j]+1 > length[i]){
length[i] = length[j]+1;
}
}
}
int maxLength = length[0];
for(int i = 1;i<size;i++){
if(maxLength < length[i]){
maxLength = length[i];
}
}
return maxLength;
}
};