leetcode 之 Longest Increasing Subsequence

题目描述:

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) complexity.

Follow up: Could you improve it to O(n log n) time complexity? 

即 给定一个无序的数组,找到最长的递增子序列。 返回其长度

解法1: 动态规划的解法。 设maxIns[i]  为以第i个数结尾的最长递增子序列的长度。

则maxIns[i+1]:

遍历0~i, 若nums[i+1] > nums[j] (j ~(0, i))  maxIns[i+1] = max(maxIns[i+1] , maxIns[i]+1)

算法的时间复杂度为o(n2), 空间复杂度为o(n), 代码如下:

 1 class Solution(object):
 2     def lengthOfLIS(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         ln = len(nums)
 8         if ln == 1 or ln == 0:
 9             return ln
10         lgst = [1]*(ln+1)
11         for i in range(1, ln):
12             for j in range(0, i):
13                 if nums[i] > nums[j]:
14                     lgst[i] = max(lgst[j]+1, lgst[i])
15         return max(lgst)
~~~~~
原文地址:https://www.cnblogs.com/missmzt/p/5587393.html