Longest common subsequence (correct establishment of python two-dimensional array)

leetcode question 1143

 Here we choose to use dynamic programming to solve the problem, and the two strings choose to use two-dimensional arrays to solve (for the dynamic programming problem of two strings, generally speaking, a two-dimensional dp array is required)

text2 = 'babcde'    text1 = 'ace'

0 1 2 3 4 5 6
 ” “ b a b c d e
0 “ ” 0 0 0 0 0 0 0
1 a 0 0 1 1 1 1 1
2 c 0 0 1 1 2 2 2
3 e 0 0 1 1 2 2 3

As for why a null character should be inserted in front of each string, my personal understanding is that it is done deliberately to make it easier to use the surrounding data to retrieve when implementing the algorithm. That is to say, for text1[0] and text[0], their longest common subsequence (LCS) is dp[1][1], and conversely, the meaning of dp[2][4]=2 is For 'ac' and 'babc', their LCS length is 2.

The specific code is as follows:

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        def dp(i,j):
            if i ==-1 or j ==-1:
                return 0
            if text1[i]==text2[j]:
                return dp(i-1,j-1)+1
            else:
                return max(dp((i-1),j),dp(i,(j-1)))
        return dp(len(text1)-1,len(text2)-1)

The above code is implemented using recursion, so the time complexity is too high and cannot pass the test requirements. Therefore, the data can be saved in the form of memos to avoid redundant calculations and reduce the time complexity.

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:

        m = len(text1) #列
        n = len(text2) #行
        dp = [[0] * (m+1) for _ in range(n+1)] #避免在同一行进行操作
        #我们知道一维数组可以用 [0] * N 这种声明方式。但是二维数组不能用上面的声明方式,这会导致                 
        #dp 中的每行的列表是同一个 id,所以对其中一行的操作都会表现为每一行的操作
        for i in range(1,n+1):
            for j in range(1,m+1):
                if text1[j-1]==text2[i-1]:
                    print(text2[i-1],text1[j-1])
                    dp[i][j]=dp[i-1][j-1]+1
                else:
                    dp[i][j]=max(dp[i][j-1],dp[i-1][j])   
        print(dp)    
        return dp[n][m]

I encountered a problem when writing the above code. I will record it here. When forming a two-dimensional array in python, you cannot form a one-dimensional array according to the routine of forming a one-dimensional array. This will cause calculations to be performed on the same line every time. thus returning incorrect results. You need to use a for loop to generate a two-dimensional array to be the correct array.

I have just started to learn about dynamic programming problems. This is used to record some problems that I have encountered.

Guess you like

Origin blog.csdn.net/zhaodongdz/article/details/122905717