首页 > 解决方案 > python中最长重复子序列长度使用递归产生错误结果

问题描述

我正在尝试生成最长的重复子序列,但在某些情况下输出似乎不正确。

下面是我正在使用的代码块

def LRSLength(X, m, n):

    # return if the end of either string is reached
    if m == 0 or n == 0:
        return 0

    # if characters at index `m` and `n` matches and the index are different
    if X[m - 1] == X[n - 1] and m!=n:
        return LRSLength1(X, m - 1, n - 1) + 1

    # otherwise, if characters at index `m` and `n` don't match
    return max(LRSLength(X, m, n - 1), LRSLength(X, m - 1, n))

虽然,当我打电话时:

LRSLength([1,1],2,2),输出=1。

LRSLength1([1,1,1,1],4,4),输出=3

LRSLength1([1,1,1,1,2,2,1,1,1,1,1],11,11),输出=8

谁能帮助我哪里出错了?

标签: pythonrecursiondynamic-programminglongest-substring

解决方案


推荐阅读