用动态规划方法实现最长公共子序列问题

用动态规划方法实现最长公共子序列问题

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  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值