动态规划——最长公共子序列(LCS)
最長(zhǎng)公共子序列的問(wèn)題描述為:
?
下面介紹動(dòng)態(tài)規(guī)劃的做法。
令 dp[i][j]?表示字符串 A?的 i?號(hào)位與字符串 B?的?j?號(hào)位之前的 LCS?長(zhǎng)度(下標(biāo)從 1?開(kāi)始),如 dp[4][5]?表示 "sads"?與 “admin"?的 LCS?長(zhǎng)度。那么可以根據(jù) A[i]?和 B[j]?的情況,分為兩種決策:
由此可以得到狀態(tài)轉(zhuǎn)移方程:
$dp[i][j]=\left\{\begin{matrix}dp[i-1][j-1]+1,A[i]==B[j]\\ max\left \{ dp[i-1][j], dp[i][j-1] \right\},A[i]!=B[j]\end{matrix}\right.$
邊界:dp[i][0] = dp[0][j] = 0 (0≤i≤n, 0≤j≤m)
這樣狀態(tài) dp[i][j]?只與其之前的狀態(tài)有關(guān),由邊界出發(fā)即可得到整個(gè) dp?數(shù)組,最終 dp[n][m]?就是需要的答案,時(shí)間復(fù)雜度為 O(nm)。
代碼如下:
1 /* 2 最長(zhǎng)公共子序列(LCS) 3 */ 4 5 #include <stdio.h> 6 #include <string.h> 7 #include <math.h> 8 #include <stdlib.h> 9 #include <time.h> 10 #include <stdbool.h> 11 12 #define maxn 100 13 char A[maxn], B[maxn]; 14 int dp[maxn][maxn]; 15 16 // 求較大值 17 int max(int a, int b) { 18 return a>b ? a : b; 19 } 20 21 int main() { 22 scanf("%s %s", A+1, B+1); // 從下標(biāo)為 1 開(kāi)始輸入 23 int lenA = strlen(A+1); // 讀取長(zhǎng)度也從 1 開(kāi)始 24 int lenB = strlen(B+1); 25 int i, j; 26 for(i=0; i<=lenA; ++i) { // 邊界 27 dp[i][0] = 0; 28 } 29 for(j=0; j<=lenB; ++j) { 30 dp[0][j] = 0; 31 } 32 for(i=1; i<=lenA; ++i) { // 狀態(tài)轉(zhuǎn)移方程 33 for(j=1; j<=lenB; ++j) { 34 if(A[i] == B[j]) { 35 dp[i][j] = dp[i-1][j-1] + 1; 36 } else { 37 dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 38 } 39 } 40 } 41 printf("%d\n", dp[lenA][lenB]); // dp[lenA][lenB] 是答案 42 43 return 0; 44 }?
轉(zhuǎn)載于:https://www.cnblogs.com/coderJiebao/p/Algorithmofnotes29.html
總結(jié)
以上是生活随笔為你收集整理的动态规划——最长公共子序列(LCS)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 您好,plosone提交稿件两个月了一直
- 下一篇: a+b_1