Dub*_*bby 9 string algorithm recursion dynamic-programming
公共子串算法:
LCS(x,y) = 1+ LCS(x[0...xi-1],y[0...yj-1] if x[xi]==y[yj]
else 0
Run Code Online (Sandbox Code Playgroud)
现在动态规划解决方案很好理解。但是我无法找出递归解决方案。如果有多个子串,则上述算法似乎失败了。
例如:
x = "LABFQDB" and y = "LABDB"
Run Code Online (Sandbox Code Playgroud)
应用上述算法
1+ (x= "LABFQD" and y = "LABD")
1+ (x= "LABFQ" and y = "LAB")
return 0 since 'Q'!='B'
Run Code Online (Sandbox Code Playgroud)
返回的值将是 2,而我应该是 3?
有人可以指定递归解决方案吗?
Zan*_* XY 11
尽量避免任何混淆,您要问的是longest common substring
,不是longest common subsequence
,它们非常相似但有差异。
The recursive method for finding longest common substring is:
Given A and B as two strings, let m as the last index for A, n as the last index for B.
if A[m] == B[n] increase the result by 1.
if A[m] != B[n] :
compare with A[m -1] and B[n] or
compare with A[m] and B[n -1]
with result reset to 0.
Run Code Online (Sandbox Code Playgroud)
以下是没有应用记忆的代码,以便更好地说明算法。
The recursive method for finding longest common substring is:
Given A and B as two strings, let m as the last index for A, n as the last index for B.
if A[m] == B[n] increase the result by 1.
if A[m] != B[n] :
compare with A[m -1] and B[n] or
compare with A[m] and B[n -1]
with result reset to 0.
Run Code Online (Sandbox Code Playgroud)
小智 0
long max_sub(int i, int j)
{
if(i<0 or j<0)
return 0;
if(s[i]==p[j])
{
if(dp[i][j]==-1)
dp[i][j]=1+max_sub(i-1,j-1);
}
else
{
dp[i][j] = 0;
}
if(i-1>=0 and dp[i-1][j]==-1)
max_sub(i-1, j);
if(j-1>=0 and dp[i][j-1]==-1)
max_sub(i, j-1);
return dp[i][j];
}
Run Code Online (Sandbox Code Playgroud)
您的代码的问题似乎是您没有尝试所有 n^2 种可能性。