问题:给定两个字符串‘X’和‘Y’,找出最长的公共子字符串的长度。
我的解决方案一直在运行,没有达到基本条件。我不明白这是为什么?
我看过DP解决方案,但在互联网上找不到一个令人满意的递归解决方案。
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(最长公共子串的长度)
发布于 2018-01-15 08:15:49
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应该是使用++的incremented.Since,在两个调用中都传递增量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));
}发布于 2018-01-15 08:14:06
值得注意的是,您在递归调用函数时减少了索引。不应该这样做,因为索引在返回时会自动减少。当字符不相同时,您应该继续增加一个索引,然后继续增加另一个索引。
类似于(专注于递归,而不是正确性):
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;https://stackoverflow.com/questions/48258718
复制相似问题