①确定状态:dp[i][j]表示长度[0, i - 1]的字符串text1与长度[0, j - 1]的字符串text2的最长公共子序列;
②转移方程:dp[i][j]=dp[i−1][j−1]+1, 当 text1[i - 1] == text2[j - 1];
dp[i][j]=Math.max(dp[i−1][j],dp[i][j−1]), 当 text1[i - 1] != text2[j - 1];
③初始条件和边界情况:dp[i][0] = 0;dp[0][j] = 0;
④计算顺序:因为 dp[i][j] 由 dp[i−1][j−1],dp[i - 1][j] 和 dp[i][j - 1]推出,所以从小到大遍历。
长公共子序列题解https://leetcode.cn/problems/longest-common-subsequence/solution/fu-xue-ming-zhu-er-wei-dong-tai-gui-hua-r5ez6/
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
//dp[i][j]表示长度[0, i - 1]的字符串text1与长度[0, j - 1]的字符串text2的最长公共子序列
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; 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[m][n];
}
}


