Python实现最长公共子序列 - 动态规划方法

# -*- coding:utf-8 -*-
__author__ = 'yangxin_ryan'


class LongestCommonSubsequence(object):

    def lcs(self, s1, s2):
        """
        先生成矩阵,然后循环便利矩阵去比较,
        记录0代表是不同
        记录1代表是相同
        记录2代表是值不同并且取得是左侧的值(左侧更大)
        记录3代表是值不同并且取得是上面的值(右侧更大)
        然后最后的
        循环便利矩阵
        :param s1:
        :param s2:
        :return:
        """
        size1 = len(s1) + 1
        size2 = len(s2) + 1
        # 程序多加一行,一列,方便后面代码编写(从0开始)
        data_path = [[["", 0] for j in list(range(size2))] for i in list(range(size1))]
        for i in list(range(1, size1)):
            data_path[i][0][0] = s1[i - 1]
        for j in list(range(1, size2)):
            data_path[0][j][0] = s2[j - 1]
        print("init data ...")
        print(data_path)
        for i in list(range(1, size1)):
            for j in list(range(1, size2)):
                if s1[i - 1] == s2[j - 1]:
                    data_path[i][j] = ['↖', data_path[i - 1][j - 1][

你可能感兴趣的:(Python,算法,ACM)