Leetcode** 300. Longest Increasing Subsequence
作者:互联网
Description: Given an integer array nums
, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7]
is a subsequence of the array [0,3,1,6,2,2,7]
.
Link: 300. Longest Increasing Subsequence
Examples:
Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1
思路: 这是一道动态规划题目。dp[i]表示到第i个元素,的最长递增子序列。dp[0] = 1; dp[i] = max{dp[j]+1} if nums[j] < nums[i] and j < i,否则dp[i] = 1.找到i前面以小于nums[i]结尾的最长子序列,它可以和nums[i]构成新的最长子序列,更新dp,如果i前面没有比它小的,那么dp[i] = 1。
class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) dp = [0]*n dp[0] = 1 for i in range(1, n): tmp = 0 for j in range(i): if nums[j] < nums[i]: tmp = max(tmp, dp[j]) dp[i] = tmp + 1 return max(dp)
日期: 2021-04-16 又周五了,我还没干啥呢,快快进步吧
标签:tmp,nums,300,subsequence,Subsequence,Input,array,Increasing,dp 来源: https://www.cnblogs.com/wangyuxia/p/14668527.html