python--lintcode76.最长上升子序列

描述

给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度。

您在真实的面试中是否遇到过这个题?  是

说明

最长上升子序列的定义:

最长上升子序列问题是在一个无序的给定序列中找到一个尽可能长的由低到高排列的子序列,这种子序列不一定是连续的或者唯一的。
https://en.wikipedia.org/wiki/Longest_increasing_subsequence

样例

给出 [5,4,1,2,3],LIS 是 [1,2,3],返回 3
给出 [4,2,4,5,3,7],LIS 是 [2,4,5,7],返回 4

挑战

要求时间复杂度为O(n^2) 或者 O(nlogn)

这一题开一个dp数组,数组中第i个位置存的是以i为结尾的子序列里面包含的最长上升子序列的数字个数。那么有如下递推关系:

dp[i] = max{dp[j] + 1,dp[i]}     其中j < i && nums[j] < nums[i]

代码如下:

class Solution:
    """
    @param nums: An integer array
    @return: The length of LIS (longest increasing subsequence)
    """
    def longestIncreasingSubsequence(self, nums):
        # write your code here
        dp=[1 for i in range(len(nums))]
        maxresult=0
        for i in range(1,len(nums)):
            for j in range(0,i):
                if(nums[j]<nums[i]):
                    dp[i]=max(dp[i],dp[j]+1)
            maxresult=max(dp[i],maxresult)
        return maxresult




s = Solution()
print(s.longestIncreasingSubsequence([5,4,1,2,3]))

猜你喜欢

转载自blog.csdn.net/wenqiwenqi123/article/details/81327682