leetcode 之 Longest Increasing Subsequence
Posted 鱼儿慢慢游~~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于leetcode 之 Longest Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 之Longest Common Prefix(34)
LeetCode 之 Longest Valid Parentheses(栈)
LeetCode之 Longest Substring Without Repeating Characters
leetcode05- Longest Palindromic Substring之Java版本