[leetcode300] Longest Increasing Subsequence 解题报告

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,,an1} A [ N ] = { a 0 , a 1 , a 2 , ⋯ , a n − 1 } ,假设我们想求以 aj a j 结尾的最大递增子序列长度,设为 L(i) L ( i ) ,则:

L(i)={max{L(j)}+1 (ajai,0j<i)1 (aj>ai,0j<i) L ( i ) = { m a x { L ( j ) } + 1   ( a j ≤ a i , 0 ≤ j < i ) 1   ( a j > a i , 0 ≤ j < i )

即以 ai a i 结尾的最长递增子序列长度为以 {a0,a1,a2,,ai1} { a 0 , a 1 , a 2 , ⋯ , a i − 1 } 中小于 ai a i 的数 aj a j 结尾的最长子序列长度加1的最大值。若 ai a i 小于 {a0,a1,a2,,ai1} { 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值