最长公共子序列
力扣题目链接
class Solution {
public:
int longestCommonSubsequence ( string text1, string text2) {
int len1 = text1. length ( ) ;
int len2 = text2. length ( ) ;
vector< vector< int >> dp ( len1+ 1 , vector< int > ( len2+ 1 , 0 ) ) ;
for ( int i = 1 ; i <= len1; i++ ) {
for ( int j = 1 ; j <= len2; j++ ) {
if ( text1[ i- 1 ] == text2[ j- 1 ] ) {
dp[ i] [ j] = max ( dp[ i- 1 ] [ j- 1 ] + 1 , max ( dp[ i- 1 ] [ j] , dp[ i] [ j- 1 ] ) ) ;
}
else {
dp[ i] [ j] = max ( dp[ i- 1 ] [ j] , dp[ i] [ j- 1 ] ) ;
}
}
}
return dp[ len1] [ len2] ;
}
} ;
不相交的线
力扣题目链接
class Solution {
public:
int maxUncrossedLines ( vector< int > & nums1, vector< int > & nums2) {
int len1 = nums1. size ( ) ;
int len2 = nums2. size ( ) ;
vector< vector< int >> dp ( len1+ 1 , vector< int > ( len2+ 1 , 0 ) ) ;
for ( int i = 1 ; i <= len1; i++ ) {
for ( int j = 1 ; j <= len2; j++ ) {
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[ len1] [ len2] ;
}
} ;
最大子序和
力扣题目链接
class Solution {
public:
int maxSubArray ( vector< int > & nums) {
vector< int > dp ( nums. size ( ) , 0 ) ;
int result = nums[ 0 ] ;
dp[ 0 ] = nums[ 0 ] ;
for ( int i = 1 ; i < nums. size ( ) ; i++ ) {
dp[ i] = max ( dp[ i- 1 ] , 0 ) + nums[ i] ;
result = max ( result, dp[ i] ) ;
}
return result;
}
} ;
判断子序列
力扣题目链接
class Solution {
public:
bool isSubsequence ( string s, string t) {
int len1 = s. length ( ) ;
int len2 = t. length ( ) ;
vector< vector< bool>> dp ( len1+ 1 , vector< bool> ( len2+ 1 , false) ) ;
for ( int i = 0 ; i <= len2; i++ ) {
dp[ 0 ] [ i] = true;
}
for ( int i = 1 ; i <= len1; i++ ) {
for ( int j = i; j <= len2; j++ ) {
if ( dp[ i] [ j- 1 ] ) {
dp[ i] [ j] = true;
}
else if ( s[ i- 1 ] == t[ j- 1 ] ) {
dp[ i] [ j] = dp[ i- 1 ] [ j- 1 ] ;
}
}
}
return dp[ len1] [ len2] ;
}
} ;