1. 程式人生 > >最長公共子序列(可列印所有子序列)

最長公共子序列(可列印所有子序列)

import java.util.HashSet;
public class MyLCS {


	public static int dp[][] = null;
	public static String str1 = null;
	public static String str2 = null;
	//用於存放結果
	public static char[] result = null;
	//用於結果去重
	public static HashSet<String> set = new HashSet<String>();
	public static void printLCS(int x, int y, int cur){
		if(x >= str1.length() || y >= str2.length()){
			String str = new String(result);
			if(set.contains(str)) return;
			set.add(str);
			System.out.println(str);
			return;
		}
		if(str1.charAt(x) == str2.charAt(y)){
			result[cur] = str1.charAt(x);
			printLCS(x+1,y+1,cur+1);
		}else if(dp[x+1][y] > dp[x][y+1]){
			printLCS(x+1,y,cur);
		}else if(dp[x+1][y] < dp[x][y+1]){
			printLCS(x,y+1,cur);
		}else{
			printLCS(x+1,y,cur);
			printLCS(x,y+1,cur);
		}
	}
	public static void getLCS(){
		for(int i=str1.length()-1; i>=0; i--){
			for(int j=str2.length()-1; j>=0; j--){
				if(str1.charAt(i) == str2.charAt(j)){
					dp[i][j] = dp[i+1][j+1] + 1;
				}else{
					dp[i][j] =Math.max(dp[i+1][j], dp[i][j+1]);
				}
			}
		}
		result = new char[dp[0][0]];
		System.out.println(dp);
		printLCS(0,0,0);
	}
 	public static void main(String[] args) {
 		str1 = "cegefkh";
		str2 = "acgbfhk";
		dp = new int[str1.length() + 1][str2.length()+1];
		getLCS();
	}
}