打印出最长公共子序列

题目

接着题目最长公共子序列,这次返回公共子序列,上一题仅返回了公共子序列长度而已

思路

  • 自己举例画出dp数组后,可以发现,公共子序列出现在每次相等的第一次的字母
- 在判断text1[i-1] == text2[j-1]时保存一下即可

代码

def longestCommonSubsequence(text1, text2):
    row = len(text1) + 1
    col = len(text2) + 1
    dp = [[0]*col for i in range(row)]
    res = []
    for i in range(1, row):
        for j in range(1, col):
            if text1[i-1] == text2[j-1]:
                res.append(text1[i-1])
                dp[i][j] += dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
    return dp[-1][-1], res


if __name__ == '__main__':
    res_len, res = longestCommonSubsequence("abcde", "ace")
    print(res)
posted @ 2023-03-14 21:20  时光如你般美好  阅读(30)  评论(0编辑  收藏  举报