[英]Error in Recursive solution to Longest Common Substring
问题:给定两个字符串“ X”和“ Y”,找出最长的公共子字符串的长度。
我的解决方案一直运行,没有达到基本条件。 我不明白为什么会这样?
我看过DP解决方案,但在Internet上找不到针对此问题的令人满意的递归解决方案。
int lcs_calc(string str1, string str2, int i_1, int i_2, int lcs, int c_lcs)
{
if (i_1 >= str1.length() || i_2 >= str2.length())
{
//end. base cond
return lcs;
}
if (str1[i_1] == str2[i_2])
{
c_lcs++;
if (c_lcs > lcs) lcs = c_lcs;
return lcs_calc(str1, str2, ++i_1, ++i_2, lcs, c_lcs);
}
else
{
if (c_lcs == 0)
{
return max(lcs_calc(str1, str2, ++i_1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, ++i_2, lcs, c_lcs));
}
else
{
c_lcs = 0;
return max(lcs_calc(str1, str2, --i_1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, --i_2, lcs, c_lcs));
}
}
}
初始参数:
str1 =“ AABC”
str2 =“ ABCD”
i_1 = 0(第一个字符串的索引)
i_2 = 0(第二个字符串的索引)
c_lcs = 0(当前公共子串的长度)
lcs = 0(最长公共子串的长度)
return max(lcs_calc(str1, str2, ++i_1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, ++i_2, lcs, c_lcs));
在第一个调用中,仅应将i_1
递增,而在第二个调用中,仅i_2
递增。由于使用++
,因此在两个调用中均传递了递增的i_1
。 您应该理解,在第一次调用++i_1
之后,在第二次调用lcs_calc()
i_1
也将作为增量值传递,这不是您想要的。
另外,您不需要其他情况。
else
{
return max(lcs_calc(str1, str2, i_1+1, i_2, lcs, c_lcs), lcs_calc(str1, str2, i_1, i_2+1, lcs, c_lcs));
}
令人惊讶的是,您在递归调用函数时减少了索引。 不应该这样做,因为索引在返回时会自动减少。 当字符不同时,您应该继续增加一个索引,然后继续增加另一个索引。
类似于(专注于递归,而不是正确性):
if (length reached): return c_lcs
if same: lcs = rec(str1, str2, i1+1, i2+1, c_lcs)
lcs = max(lcs, rec(str1, str2, i1+1, i2, 0))
lcs = max(lcs, rec(str1, str2, i1, i2+1, 0))
return lcs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.