Leetcode 300. 最长上升子序列

题目要求:

给定一个无序的整数数组,找到其中最长上升子序列的长度。

实例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

动态规划:

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        dp = [1 for i in range(len(nums))]
        for i in range(len(nums)):
            for j in range(0, i):
                if nums[j] < nums[i]:
                    dp[i] = max(dp[j]+1, dp[i])
        _max = 0
        for i in dp:
            if i > _max:
                _max = i
        return _max

分析

其中dp[i] 代表以第i个元素为结尾的上升子序列的最长长度
状态转移方程: 根据数学归纳法,假设dp[i-1]已知,推导
如果写不出来就要考虑dp的含义对不对,或者dp是否需要用二维数组

二分查找:

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        # 二分查找
        top = [0 for i in range(len(nums))]
        heaps = 0
        for i in range(len(nums)):
            left = 0
            right = heaps
            while left < right:
                mid = (left + right) // 2
                if top[mid] < nums[i]:
                    left = mid + 1
                elif top[mid] > nums[i]:
                    right  = mid
                else:
                    right = mid
            if left == heaps:
                heaps += 1
            top[left] = nums[i]
        return heaps

分析:

思想就是蜘蛛纸牌分堆。其中二分查找有很多细节需要注意

参考题解:

二分查找细节详解: https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/er-fen-cha-zhao-suan-fa-xi-jie-xiang-jie-by-labula/
最长上升子序列: https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-she-ji-fang-fa-zhi-pai-you-xi-jia/

posted @ 2019-10-28 15:09  Howardwang  阅读(117)  评论(0编辑  收藏  举报