算法学习——动态规划 例题:最长公共子序列问题(java)详解过程

package DTGH;

/*
    最长公共子序列
        一个给定序列的子序列是在该序列中删去若千元素后得到的序列
        给定两个序列X和Y ,当另一-序列Z既是X的子序列又是Y的子序列时,称Z是序
        列X和Y的公共子序列
    最长公共子序列,
.       X=(A,B,C,B,D,A,B) Y= (B,D,C,A,B, A)●(B,C,B,A) (B,D, A, B)
 */
public class LongSonString {
    // 暴力法解决
    public int search(int xi, int yi, char[] X, char[] Y) {
        //dp返回条件
        if (xi == x.length  || yi == y.length) {
            return 0;
        }
        //判断当前xi和yi是否相等
        if (x[xi] == y[yi]) {
            return bl(xi + 1, yi + 1, x, y) + 1;
        }
        return Math.max(bl(xi + 1, yi, x, y), bl(xi, yi + 1, x, y));
    }

    //记忆化搜索动态的雏形
   //记忆化搜索 res 初始化为-1
    public static int jyh(int xi, int yi, char[] x, char[] y,int[][] res) {
        //dp返回条件
        if (xi == x.length - 1 || yi == y.length) {
            return 0;
        }
        if(res[xi][yi]!=-1){
            return res[xi][yi];
        }
        //判断当前xi和yi是否相等
        if (x[xi] == y[yi]) {
             res[xi][yi]=bl(xi + 1, yi + 1, x, y) + 1;
            return res[xi][yi];
        }else {
            res[xi][yi] = Math.max(bl(xi + 1, yi, x, y), bl(xi, yi + 1, x, y));
            return res[xi][yi];
        }
    }
    //动态规划
    public static int dtgh(char[] x,char[] y){
        int res[][] =new int[x.length+1][y.length+1];
        for (int i = 1; i <=x.length ; i++) {
            for (int j = 1; j <=y.length ; j++) {
                if (x[i-1]==y[j-1]){
                    res[i][j]=res[i-1][j-1]+1;
                }else{
                    res[i][j]=Math.max(res[i-1][j],res[i][j-1]);
                }
            }
        }
        return res[x.length][y.length];
    }

    public static void main(String[] args) {
        LongSonString a = new LongSonString();
        char[] x = {'A', 'B', 'C', 'B', 'D', 'A', 'B'};
        //char[] y = {'A', 'B', 'B','B', 'D', 'A', 'B'};
        char[] y = {'B', 'D', 'C', 'A', 'B', 'A'};
        int[][] res = new int[x.length][y.length];
        for (int i = 0; i < x.length; i++) {
            for (int j = 0; j < y.length; j++) {
                res[i][j] = -1;
            }
        }

         System.out.println(DTGH_LongPublicString.bl(0, 0, x, y));
        System.out.println(DTGH_LongPublicString.dtgh(x, y));
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值