1143.最长公共子序列
class Solution ( object ) :
def longestCommonSubsequence ( self, text1, text2) :
"""
:type text1: str
:type text2: str
:rtype: int
"""
dp = [ [ 0 ] * ( len ( text2) + 1 ) for i in range ( len ( text1) + 1 ) ]
for j in range ( 1 , len ( text1) + 1 ) :
for k in range ( 1 , len ( text2) + 1 ) :
if text1[ j- 1 ] == text2[ k- 1 ] :
dp[ j] [ k] = dp[ j- 1 ] [ k- 1 ] + 1
else :
dp[ j] [ k] = max ( dp[ j- 1 ] [ k] , dp[ j] [ k- 1 ] )
return dp[ - 1 ] [ - 1 ]
1035.不相交的线
class Solution ( object ) :
def maxUncrossedLines ( self, nums1, nums2) :
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
dp = [ [ 0 ] * ( len ( nums2) + 1 ) for _ in range ( len ( nums1) + 1 ) ]
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
else :
dp[ i] [ j] = max ( dp[ i- 1 ] [ j] , dp[ i] [ j- 1 ] )
return dp[ - 1 ] [ - 1 ]
53. 最大子序和
题目链接:53. 最大子序和 result其实相当于保存了dp[i-1]不动的结果,同时避免出现非连续子序和的情况
class Solution ( object ) :
def maxSubArray ( self, nums) :
"""
:type nums: List[int]
:rtype: int
"""
dp = [ 0 ] * len ( nums)
result = - float ( 'inf' )
for i in range ( len ( nums) ) :
dp[ i] = max ( dp[ i- 1 ] + nums[ i] , nums[ i] )
result = max ( result, dp[ i] )
return result
392.判断子序列
题目链接:392.判断子序列 本质还是求最长公共子序列,如果当前ij不匹配,则在t中删除i(即变为i-1)
class Solution ( object ) :
def isSubsequence ( self, s, t) :
"""
:type s: str
:type t: str
:rtype: bool
"""
dp = [ [ 0 ] * ( len ( s) + 1 ) for _ in range ( len ( t) + 1 ) ]
for i in range ( 1 , len ( t) + 1 ) :
for j in range ( 1 , len ( s) + 1 ) :
if t[ i- 1 ] == s[ j- 1 ] :
dp[ i] [ j] = dp[ i- 1 ] [ j- 1 ] + 1
else :
dp[ i] [ j] = dp[ i- 1 ] [ j]
return True if dp[ - 1 ] [ - 1 ] == len ( s) else False