用动态规划方法实现最长公共子序列问题
public class LCSS {
public static void main(String args[]) {
int n,m;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
int a[] = new int [m];
int b[] = new int [n];
int w = n+1;
int y = m+1;
int c[][] = new int [w][y];
int d[][] = new int [m][n];
//使用随机数来产生数组中的元素
for(int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random()*10);
}
System.out.print("第一个数组为:");
for(int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
for(int j = 0; j < b.length; j++) {
b[j] = (int)(Math.random()*10);
}
System.out.print("第二个数组为:");
for(int i = 0; i < a.length; i++) {
System.out.print(b[i]+" ");
}
System.out.println();
System.out.print("最长公共子序列为:");
LCSlength lcs = new LCSlength();
lcs.LCS(a, b, c, d);
lcs.LCS1(m-1, n-1, a, d);
}
}
class LCSlength{
void LCS(int a[],int b[],int c[][],int d[][]) {
int i ,j;
for (i = 1; i < a.length; i++) c[i][0] = 0;
for (i = 1; i < b.length; i++) c[0][i] = 0;
for (i = 1; i < a.length; i++)
for (j = 1; j < b.length; j++)
{
if (a[i]==b[j])
{
c[i][j]=c[i-1][j-1]+1;
d[i][j]=1;
}
else if (c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
d[i][j]=2;
}
else
{ c[i][j]=c[i][j-1];
d[i][j]=3;
}
}
}
void LCS1(int i,int j,int a[],int d[][]) {
if (i ==0 || j==0) return;
if (d[i][j]== 1)
{
LCS1(i-1,j-1,a,d);
System.out.print(a[i]+" ");
}
else if (d[i][j]== 2)
LCS1(i-1,j,a,d);
else LCS1(i,j-1,a,d);
}
}
执行结果
10 10
第一个数组为:3 3 2 6 5 9 8 3 6 9
第二个数组为:8 7 9 2 6 4 7 7 0 9
最长公共子序列为:2 6 9