1143. The longest common subsequence (medium)

Ideas:

State transition equation:

Using double traversal, if the character of the subscript i of text1 is the same as the character of the subscript j of text2, then dp[i][j]=dp[i-1][j-1]+1 is based on the previous value Add 1

If they are not the same, take the case where text1 and text2 have the most common subsequences dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1])

 

Code:

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
		int m=text1.length();
		int n=text2.length();
		int[][] dp=new int[m+1][n+1];
		
		//初始化0行、0列,表示text1与空字符串text1	or	text2与空字符串text1比较返回0
		for(int i=0;i<=m;i++){
			dp[i][0]=0;
		}
		for(int i=0;i<=n;i++){
			dp[0][i]=0;
		}
		
		//从1开始遍历,
		for(int i=0;i<m;i++){
			for(int j=0;j<n;j++){
				if(text1.charAt(i)==text2.charAt(j)){
					dp[i+1][j+1]=dp[i][j]+1;
				}else{
					dp[i+1][j+1]=Math.max(dp[i][j+1],dp[i+1][j]);
				}
			}
		}
		
		return dp[m][n];

	}
}

 

break down:

1) Due to boundary issues:

    i) Row 0 and column 0 represent 0 characters, so all rows and columns 0 should be set to 0 during initialization.

    ii) One more when declaring dp, dp[m+1][n+1]

    iii) When initializing, the boundary condition is to reach m and n, i<=m, i<=n

    iiii) When traversing, start from 0, because text1.charAt(1) represents the second character of the string. And dp[1][1] means that the first character of text1 is compared with the second character of text2

    iiiii) Return the result dp[m][n] instead of dp[m-1][n-1]

 

2) Here dp is the second form, the current value depends on all previous calculated values

Is interval planning

Guess you like

Origin blog.csdn.net/di_ko/article/details/115262012