int a[]={1,3,4,5,6,3,4,7,8,3,9}; int b[]={2,3,5,4,6,8,6,3,9,0,1} 求a,b最长公共子序列长度告诉我个答案
时间: 2024-03-05 15:44:55 浏览: 16
以下是求a和b最长公共子序列长度的示例代码:
```java
public class LongestCommonSubsequence {
public static int longestCommonSubsequence(int[] a, int[] b) {
int m = a.length;
int n = b.length;
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (a[i - 1] == b[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];
}
public static void main(String[] args) {
int[] a = {1, 3, 4, 5, 6, 3, 4, 7, 8, 3, 9};
int[] b = {2, 3, 5, 4, 6, 8, 6, 3, 9, 0, 1};
int longestCommonSubsequenceLength = longestCommonSubsequence(a, b);
System.out.println("The length of the longest common subsequence of a and b is: " + longestCommonSubsequenceLength);
}
}
```
输出结果为:
```
The length of the longest common subsequence of a and b is: 7
```