动态规划求解两个字符串的最长公共子序列

最简单的递归便宜方程为

LCS(m,n):求s1[0...m]   和s2[0...n] 的最长公共子序列changdu

偏移状态:

s1[m] ==s2[n]?1+LCS(m-1,n-1):max(LCS(m-1,n),LCS(m,n-1))

详细代码:

   

public class Wigglemaxlength {
    private  char[] s1;
    private  char[] s2;
    public int wigglemaxlength(char[] s1, char[] s2) {
        int m = s1.length, n = s2.length;
        if(m==0||n==0)return 0;
        this.s1=s1;this.s2=s2;
        return LCS(m-1,n-1);
    }

    private int LCS(int m, int n) {
        if(m<0||n<0)return 0;
        return s1[m]==s2[n]?1+LCS(m-1,n-1):Math.max(LCS(m-1,n ),LCS(m,n-1));
    }
    public static void main(String[] args){
        Wigglemaxlength wigglemaxlength=new Wigglemaxlength();
        System.out.println(wigglemaxlength.wigglemaxlength(new char[]{'A','B','C','D'},new char[]{'A','E','B','D'} ));
    }
}

以上只是只是递归,时间复杂度高,使用记忆话搜索来优化,剪枝:

public class Wigglemaxlength {
    private  char[] s1;
    private  char[] s2;
    private int[][] memo;
    public int wigglemaxlength(char[] s1, char[] s2) {
        int m = s1.length, n = s2.length;
        if(m==0||n==0)return 0;
        this.s1=s1;this.s2=s2;
        memo=new int[m][n];
        return LCS(m-1,n-1);
    }

    private int LCS(int m, int n) {
        if(m<0||n<0)return 0;
        if( memo[m][n]!=0)return memo[m][n];
        memo[m][n]=s1[m]==s2[n]?1+LCS(m-1,n-1):Math.max(LCS(m-1,n ),LCS(m,n-1));
        return memo[m][n];
    }
    public static void main(String[] args){
        Wigglemaxlength wigglemaxlength=new Wigglemaxlength();
        System.out.println(wigglemaxlength.wigglemaxlength(new char[]{'A','B','C','D'},new char[]{'A','E','B','D'} ));
    }
}

 

 

 

 

你可能感兴趣的:(java,算法)