1143. Self-reflection of the longest common subsequence for dynamic programming

Today I saw a sentence, the question of algorithms, first of all, to sort out the ideas, not the algorithms or the equations, but the code-style presentation of my ideas before writing the code. Let ’s summarize the dynamic planning today. This aspect has always been our own weakness. If it is said to be weak, it is better to say that the questions do not match the ideas. Many of the dynamic planning directly made by yourself are obvious, but the thinking is not particularly clear. Many of the dynamic planning are The biggest substring, what is the biggest subsequence problem, the largest subsequence question is listed below:

First make sure that this question is a dynamic programming question type, we mark i and j at any position, i is the mark position of text1, j is the mark position of text2, if the characters at the positions of i and j are the same, then dp [i ] What is [j] equal to? Is it equal to dp [i-1] [j] or dp [i] [j-1]? That is:

(1) If the last bit of S is equal to the last bit of T, the maximum subsequence is the maximum of {s1, s2, s3 ... si-1} and {t1, t2, t3 ... tj-1} Subsequence + 1

(2) If the last bit of S is not equal to the last bit of T, then the maximum subsequence is

① {s1, s2, s3..si} and {t1, t2, t3 ... tj-1} maximum subsequence

② {s1, s2, s3 ... si-1} and {t1, t2, t3 .... tj} maximum subsequence

The maximum value of the above two self-sequences

The dynamic equation has been generated, then we post the code as follows:

    public int longestCommonSubsequence(String text1, String text2) {
        int n1 = text1.length(), n2 = text2.length();
        int[][] dp = new int[n1 + 1][n2 + 1];
        for (int i = 1; i <= n1; i++) {
            for (int j = 1; j <= n2; j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[n1][n2];
    }

 

Published 17 original articles · Likes0 · Visits 154

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105013284
Recommended