Java 输出全部最长公共子序列
import java.util.HashSet;
import java.util.Set;
public class LCSProblem {
static Set<String> list = new HashSet<>();
static StringBuilder temp = new StringBuilder();
public static void main(String[] args)
{
String[] x = {"", "2", "4", "6", "4", "6"};
String[] y = {"", "6", "2", "5", "4", "6"};
int[][] b = getLength(x, y);
storeLCS(b, x, x.length-1, y.length-1);
for(String item:list){
System.out.println(item);
}
}
/**
* @param x
* @param y
* @return 返回一个记录决定搜索的方向的数组
*/
public static int[][] getLength(String[] x, String[] y)
{
// 记录方向
int[][] b = new int[x.length][y.length];
// 记录长度
int[][] c = new int[x.length][y.length];
for(int i=1; i<x.length; i++)
{
for(int j=1; j<y.length; j++)
{
// 相等则斜上对角赋值
if( x[i] == y[j])
{
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = 1;
}
// 左边和上边比较,谁大谁赋值
else if(c[i-1][j] > c[i][j-1])
{
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
// 左边和上边比较,谁大谁赋值
else if(c[i-1][j] < c[i][j-1])
{
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
// 相等则都可, b标记为4
else
{
c[i][j] = c[i][j-1];
b[i][j] = 4;
}
}
}
return b;
}
/**
*
* @param b
* @param x
* @param i
* @param j
*/
public static void storeLCS(int[][] b, String[] x, int i, int j)
{
if(i == 0 || j == 0){
list.add(temp.toString());
return;
}
if(b[i][j] == 1)
{
temp.insert(0, x[i] + " ");
storeLCS(b, x, i-1, j-1);
temp.delete(0, 2);
}
else if(b[i][j] == 2)
{
storeLCS(b, x, i-1, j);
}
else if(b[i][j] == 3)
{
storeLCS(b, x, i, j-1);
}else if(b[i][j] == 4)
{
storeLCS(b, x, i-1, j);
storeLCS(b, x, i, j-1);
}
}
}
感谢 此博客为我解惑