动态规划,求最长公共子序列
引进一个二维数组Array[][],用Array[i][j]记录A[i]与B[j] 的LCS 的长度,sign[i][j]记录ARRAY[i][j]是通过哪一个子问题的值求得的,以决定搜索的方向。
问题的递归式写成:
回溯输出最长公共子序列过程:
// LCSLength.cpp : Defines the entry point for the console application. // #include "StdAfx.h" #include "iostream" #include "string" #include "vector" using namespace std; vector< vector<int> > sign; vector< vector<int> > array ; string A; string B; void printsign(vector< vector<int> > & sign); int getLCSlength(string strA,string strB){ int leni = strA.length() + 1; int lenj = strB.length() + 1; int i = 0; int j = 0; // init the array array.resize(leni); for(i = 0;i<leni;i++) array[i].resize(lenj); // init the sign sign.resize(leni); for(i = 0;i<leni;i++) sign[i].resize(lenj); for(i = 1;i<leni;i++) for(j = 1;j<lenj;j++){ if(strA[i-1] == strB[j-1]){ //dp[i][j] = dp[i-1][j-1] + 1 如果X[i-1] = Y[i-1]
array[i][j] = array[i-1][j-1] + 1; sign[i][j] = 1; //"\" } else if(array[i-1][j]>=array[i][j-1]){ //下面两种情况,p[i][j] = max{ dp[i-1][j], dp[i][j-1] } 如果X[i-1] != Y[i-1] array[i][j] = array[i-1][j]; sign[i][j] = 2; //"^" } else{ array[i][j] = array[i][j-1]; sign[i][j] = 0; //"<-" } } return array[leni-1][lenj-1]; } void printsign(vector< vector<int> > & sign){ cout<<"~~~~~~~~~~~~~~~~~~~~"<<endl; vector< vector<int> >::iterator iti = sign.begin(); for(;iti!=sign.end();iti++){ vector<int>::iterator itj = (*iti).begin(); for(;itj != (*iti).end();itj++){ cout<<*itj<<" "; } cout<<endl; } } void printLCS(int i,int j){ if( i == 0 || j == 0) return ; if(sign[i][j] == 1){ printLCS(i-1,j-1); // cout<<"i = "<<i<<" j = "<<j<<" "; cout<<A[i-1]; } if(sign[i][j] == 2){ printLCS(i-1,j); } if(sign[i][j] == 0){ printLCS(i,j-1); } } int main(int argc, char const *argv[]) { A = "ABCBDAB"; B = "BDCABA"; cout<<"the LCS length is "<<getLCSlength(A,B)<<endl; printsign(array); printsign(sign); printLCS(A.length(),B.length()); cout<<endl; return 0; }