LeetCode--Longest Increasing Subsequence (最长递增子序列)Python
2017-12-11 10:32
513 查看
题目:
给定一串数组,返回其中的最长递增子序列的长度。例如:给定数组[10, 9, 2, 5, 3, 7, 101, 18],则其最长递增子序列为[2, 3, 7, 101],返回长度4.
解题思路:
使用动归。用Dp[i]来保存从0-i的数组的最长递增子序列的长度。如上数组Dp[0]=1,Dp[1]=1,Dp[2]=1,Dp[3]=2,Dp[4]=2。。。计算Dp[i]的值可以对Dp[i]之前数值进行遍历,如果nums[i]>nums[j],则Dp[i] = max(Dp[i],Dp[j]+1)。复杂度为O(n*n)
代码(Python):
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 0
N = len(nums)
Dp = [1]*N
for i in range(N-1):
for j in range(0,i+1):
if nums[i+1]>nums[j]:
Dp[i+1] = max(Dp[i+1],Dp[j]+1)
return max(Dp)
给定一串数组,返回其中的最长递增子序列的长度。例如:给定数组[10, 9, 2, 5, 3, 7, 101, 18],则其最长递增子序列为[2, 3, 7, 101],返回长度4.
解题思路:
使用动归。用Dp[i]来保存从0-i的数组的最长递增子序列的长度。如上数组Dp[0]=1,Dp[1]=1,Dp[2]=1,Dp[3]=2,Dp[4]=2。。。计算Dp[i]的值可以对Dp[i]之前数值进行遍历,如果nums[i]>nums[j],则Dp[i] = max(Dp[i],Dp[j]+1)。复杂度为O(n*n)
代码(Python):
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 0
N = len(nums)
Dp = [1]*N
for i in range(N-1):
for j in range(0,i+1):
if nums[i+1]>nums[j]:
Dp[i+1] = max(Dp[i+1],Dp[j]+1)
return max(Dp)
相关文章推荐
- leetcode(300)—— Longest Increasing Subsequence(最长递增子序列)
- Leetcode 300 Longest Increasing Subsequence 最长递增子序列
- 【LeetCode 300 Longest Increasing Subsequence】最长递增子序列
- 第十七章 DPL_1_D:Longest Increasing Subsequence 最长递增子序列
- longest increasing subsequence (最长递增子序列)
- [LeetCode] Number of Longest Increasing Subsequence 最长递增序列的个数
- [LintCode] Longest Increasing Subsequence 最长递增子序列
- [LeetCode] Longest Increasing Subsequence 最长递增子序列的长度
- [LintCode] Longest Increasing Continuous Subsequence 最长连续递增子序列
- leetcode300---Longest Increasing Subsequence(最长递增子序列)
- [LeetCode] Longest Continuous Increasing Subsequence 最长连续递增序列
- 最长递增子序列 (Longest Increasing Subsequence)
- poj 2533 Longest Ordered Subsequence 最长递增子序列
- 最长递增子序列(longest increasing subsequence) 问题详解
- 最长递增子序列详解(longest increasing subsequence)
- 最长递增子序列-Longest Increasing Subsequence
- Greatest Common Increasing Subsequence hdu1423 最长公共递增子序列
- Longest Increasing Subsequence(最长增长子数列)-LeetCode关于数组的思路和技巧
- 最长递增子序列 (LIS) Longest Increasing Subsequence
- 最长递增和递减子序列详解(longest increasing subsequence)