• 最长公共子序列的长度 以及输出所有最长公共子序列


    package dynamic;
    
    public class LCS {
        public static void main(String[] args) {
            String str1 = "ABCBDAB";
            String str2 = "BDCABA";
            System.out.println(LCS(str1.toCharArray(),str2.toCharArray()));
        }
        public static int LCS(char[] m,char[] n) {
            int[][] ret = new int[m.length+1][n.length+1];
            for(int i=0;i<ret.length;i++) {
                for(int j=0;j<ret[i].length;j++) {
                    if(i==0 || j==0) {
                        ret[i][j] = 0;
                    }else {
                        if(m[i-1] == n[j-1]) {
                            ret[i][j] = ret[i-1][j-1]+1;
                        }else {
                            ret[i][j] = Math.max(ret[i][j-1], ret[i-1][j]);
                        }
                    }
                }
            }
            StringBuffer sb = new StringBuffer();
            subsque(m,n,ret,m.length,n.length,sb);//输出最长公共子序列
            return ret[m.length][n.length];//返回最长公共子序列的长度
        }
        
        public static void subsque(char[] m,char[] n,int[][] ret,int p,int q,StringBuffer sb) {
            StringBuffer sb1 = new StringBuffer();
            for(int i=p,j=q ; i!=0&&j!=0 ; ) {
                if(m[i-1] == n[j-1]) {
                    sb.append(m[i-1]);
                    i--;
                    j--;
                }else {
                    if(ret[i-1][j] == ret[i][j]) {
                        sb1 = new StringBuffer(sb);
                        subsque(m,n,ret,--i,j,sb);
                        sb=sb1;
                        i++;
                    }
                    if(ret[i][j-1] == ret[i][j]) {
                        sb1 = new StringBuffer(sb);
                        subsque(m,n,ret,i,--j,sb);
                        sb=sb1;
                        j++;
                    }
                    return;
                }
            }
            System.out.println(sb.reverse());
        }
    }
  • 相关阅读:
    Netty 超时机制及心跳程序实现
    ZJUTACM
    寻找素数对
    HDU 1021 Fibonacci Again
    HDU 1019 Least Common Multiple
    HDU 1017 A Mathematical Curiosity
    HDU 1014 Uniform Generator
    HDU 1013 Digital Roots
    HDU 1008 Elevator
    Educational Codeforces Round 2 B. Queries about less or equal elements
  • 原文地址:https://www.cnblogs.com/whu-gbf/p/8574085.html
Copyright © 2020-2023  润新知