记忆化搜索和for循环解决LCS问题
来源:9-9 LCS,最短路,求动态规划的具体解以及更多
死咸鱼
2018-01-21
#include<iostream> #include<string> #include<vector> #include<memory.h> using namespace std; string s1 = "AAACCGTGAGTTATTCGTTCTAGAA"; string s2 = "CACCCCTAAGGTACCTTTGGTTC"; vector<vector<int> > memo( 100,vector<int>(100,0)); int LCS( int len1 , int len2 ) { if( len1 < 0 || len2 < 0 ) return 0; if( memo[len1][len2] != 0 ) return memo[len1][len2]; if( s1[len1] == s2[len2] ) { memo[len1][len2] = 1 + LCS( len1-1 ,len2-1 ); } else memo[len1][len2] = max( LCS(len1-1,len2) , LCS(len1,len2-1) ); return memo[len1][len2]; } int main() { cout << LCS( s1.length()-1 , s2.length()-1 ) << endl; return 0; }
#include<iostream> #include<memory.h> using namespace std; string s1 = "AAACCGTGAGTTATTCGTTCTAGAA"; string s2 = "CACCCCTAAGGTACCTTTGGTTC"; //string s1 = "357486782"; //string s2 = "13456778"; int memo[100][100]; int main() { memset( memo , 0 , sizeof(memo) ); int i , j ; for( i = 0 ; i < s1.length() ; i ++ ) { for( j = 0 ; j < s2.length() ; j ++ ) { if( s1[i] == s2[j] ) { if( i == 0 || j == 0 ) //³ö½çÁË memo[i][j] = 1; else memo[i][j] = 1 + memo[i-1][j-1]; } else { if( i == 0 || j == 0 ) memo[i][j] = 0; else memo[i][j] = max( memo[i-1][j] , memo[i][j-1] ); } } } cout << memo[s1.length()-1][s2.length()-1] << endl; return 0; }
以上是自己写的LCS的两种解决方式 麻烦波波老师帮看看写的对不对。
写回答
1回答
-
以下leetcode的问题就是LCS的问题,尝试用自己的思路完成这两个问题,看看能不能通过?:)
https://leetcode.com/problems/delete-operation-for-two-strings/description/
https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/
一个稍微拐一个弯,但思路本质也是LCS的问题可以参见这里,有兴趣的话也可以练习试试看:)
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
242018-03-05
相似问题