300.最長遞增子序列
題目鏈接:300.最長遞增子序列 dp初始化為1(最小子序列長度為1)
class Solution ( object ) : def lengthOfLIS ( self, nums) : """:type nums: List[int]:rtype: int""" dp = [ 1 ] * len ( nums) result = 1 for i in range ( 1 , len ( nums) ) : for j in range ( i) : if nums[ i] > nums[ j] : dp[ i] = max ( dp[ i] , dp[ j] + 1 ) result = max ( dp[ i] , result) return result
674. 最長連續遞增序列
class Solution ( object ) : def findLengthOfLCIS ( self, nums) : """:type nums: List[int]:rtype: int""" dp = [ 1 ] * len ( nums) result = 1 for i in range ( 1 , len ( nums) ) : if nums[ i] > nums[ i- 1 ] : dp[ i] = dp[ i- 1 ] + 1 result = max ( dp[ i] , result) return result
718. 最長重復子數組
題目鏈接:718. 最長重復子數組 dp[i][j] :以下標i - 1為結尾的A,和以下標j - 1為結尾的B,最長重復子數組長度為dp[i][j]。 (特別注意 : “以下標i - 1為結尾的A” 標明一定是 以A[i-1]為結尾的字符串 ) 定義dp[i][j]為 以下標i為結尾的A,和以下標j為結尾的B,最長重復子數組長度的問題:需要單獨處理初始化部分。
class Solution ( object ) : def findLength ( self, nums1, nums2) : """:type nums1: List[int]:type nums2: List[int]:rtype: int""" dp = [ [ 0 ] * ( len ( nums2) + 1 ) for k in range ( len ( nums1) + 1 ) ] result = 0 for i in range ( 1 , len ( nums1) + 1 ) : for j in range ( 1 , len ( nums2) + 1 ) : if nums1[ i- 1 ] == nums2[ j- 1 ] : dp[ i] [ j] = dp[ i- 1 ] [ j- 1 ] + 1 result = max ( dp[ i] [ j] , result) return result