最大公共子序列的计算逻辑

人气:350 ℃/2026-05-29 21:43

计算两个数组的最长公共子序列.

设:C[i,j] = LCS(str1[1...i],str2[1...j]),

即C[i,j]表示序列str1[1...i]和str2[1...j]的最长公共子序列的长度,则 C[m,n] = LCS(str1,str2)就是问题的解(长度为m,n).

计算公式为:

if str1[i] == str2[j] then C[i,j] = C[i-1,j-1] +1;

else if str1[i] != str2[j] then C[i,j] = max{C[i-1,j] , C[i,j-1]}.

百科

首页/问答/网名/PC版
© 2026 NiBaKu.Com All Rights Reserved.