其他分享
首页 > 其他分享> > 动态规划day10

动态规划day10

作者:互联网

115. 不同的子序列

class Solution {
    public int numDistinct(String s, String t) {
        char[] a1 = s.toCharArray(), a2 = t.toCharArray();
        if (a1.length == 0 || a2.length == 0 || a1.length < a2.length) return 0;
        int[][] dp = new int[a1.length + 1][a2.length + 1];
        //dp[i][0]代表t为空串 空串是任何字符串子串
        for (int i = 0; i <= a1.length; i++) {
            dp[i][0] = 1;
        }
        //dp[0][j]代表s为空串 初始化为0(j >= 1, 因为空串也是空串的子串)
        for (int i = 1; i <= a1.length; i++) {
            for (int j = 1; j <= a2.length; j++) {
                if (a1[i - 1] == a2[j - 1]) {
                    //相等由匹配s[i]部分(dp[i - 1][j - 1])和不匹配s[i]部分(dp[i - 1][j])组成
                    dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[a1.length][a2.length];
    }
}

 

583. 两个字符串的删除操作

class Solution {
    public int minDistance(String word1, String word2) {
        char[] a1 = word1.toCharArray(), a2 = word2.toCharArray();
        int[][] dp = new int[a1.length + 1][a2.length + 1];
        //dp[i][0]表示word2为空串 需要将word1全部删除
        for (int i = 1; i <= a1.length; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j <= a2.length; j++){
            dp[0][j] = j;
        }
        for (int i = 1; i <= a1.length; i++) {
            for (int j = 1; j <= a2.length; j++) {
                if (a1[i - 1] == a2[j - 1]) {
                    //相等不用删
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    //都删,删i和删j
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 2, Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1));
                }
            }
        }
        return dp[a1.length][a2.length];
    }
}

 

72. 编辑距离

class Solution {
    public int minDistance(String word1, String word2) {
        char[] a1 = word1.toCharArray(), a2 = word2.toCharArray();
        int[][] dp = new int[a1.length + 1][a2.length + 1];
        //dp[i][0]表示word2为空串 删除word1中字符或往word2添加字符
        for (int i = 1; i <= a1.length; i++) {
            dp[i][0] = i;
        }
        //dp[0][j]表示word1为空串 删除word2中字符或往word1添加字符
        for (int j = 1; j <= a2.length; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i <= a1.length; i++) {
            for (int j = 1; j <= a2.length; j++) {
                if (a1[i - 1] == a2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    //以word1为基准 改删增(增word1和删word2结果一样)
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 1, Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1));
                }
            }
        }
        return dp[a1.length][a2.length];
    }
}

参考:programmercarl.com

标签:int,a1,length,a2,day10,word2,动态,规划,空串
来源: https://www.cnblogs.com/lizihhh/p/dp_day10.html