算法 - 最长公共子序列记忆

发布于 2025-01-16 12:46:05 字数 848 浏览 1 评论 0原文

我正在尝试解决最长公共子序列的著名问题 - 给定 2 个字符串,返回最长的子序列。具体来说,我的目标是返回实际序列,而不是序列的长度。例如,输入“ABCD”、“BD”将输出“BD”。下面是我写的代码,我不确定我使用的“memo”哈希表有什么问题。猜测密钥不够具体,但不确定原因。如何使用递归和备忘录数组/哈希表解决这个问题?我知道它可以用自下而上的动态规划算法来解决,但想用自上而下的方法进行更多练习。谢谢你!

def longestCommonSubsequence(str1, str2):
    memo = {}
    def recurse(i, j, sub):
        key = (i, j)
        
        if i == len(str1) or j == len(str2):
            return sub
        if str1[i] == str2[j]:
            res = recurse(i + 1, j + 1, sub + [str1[i]])
            memo[key] = res
            return res
        if key in memo:
            return memo[key]
        
        first = recurse(i + 1, j, sub)
        second = recurse(i, j + 1, sub)
        
        res = first if len(first) > len(second) else second
        memo[key] = res
        return res
    
    return recurse(0, 0, [])

I am trying to solve a famous problem of longest common subsequence - given 2 strings, return the longest subsequence. To specify, my goal is to return the actual sequence, not the length of the sequence. For example, inputs "ABCD", "BD" would output "BD". Below is the code I wrote, and I'm not sure what is wrong with the "memo" hash table I'm using. Guessing the key is not specific enough but not sure why. How could I solve this problem using recursion and a memo array/ hash table? I know it is solvable with a bottom-up dynamic programming algorithm, but would like to practice more with top-down approach. Thank you!

def longestCommonSubsequence(str1, str2):
    memo = {}
    def recurse(i, j, sub):
        key = (i, j)
        
        if i == len(str1) or j == len(str2):
            return sub
        if str1[i] == str2[j]:
            res = recurse(i + 1, j + 1, sub + [str1[i]])
            memo[key] = res
            return res
        if key in memo:
            return memo[key]
        
        first = recurse(i + 1, j, sub)
        second = recurse(i, j + 1, sub)
        
        res = first if len(first) > len(second) else second
        memo[key] = res
        return res
    
    return recurse(0, 0, [])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文