双序列型动态规划例题1 Lintcode77Longest Common Subsequence

题目描述

双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence

动态规划组成部分一:确定状态

双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence
双序列型动态规划例题1 Lintcode77Longest Common Subsequence
子问题
双序列型动态规划例题1 Lintcode77Longest Common Subsequence

动态规划组成部分三:初始条件和边界情况

双序列型动态规划例题1 Lintcode77Longest Common Subsequence

动态规划组成部分四:计算顺序

双序列型动态规划例题1 Lintcode77Longest Common Subsequence

Java代码实现:

    public int longestCommonSubsequence(String A, String B) {
        int m = A.length();
        int n = B.length();
        char[] a = A.toCharArray();
        char[] b = B.toCharArray();
        int[][] f = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++)
            f[i][0] = 0;
        for (int j = 0; j <= n; j++)
            f[0][j] = 0;
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                if (a[i - 1] == b[j - 1])
                    f[i][j] = f[i - 1][j - 1] + 1;
                else
                    f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
        return f[m][n];
    }
上一篇:389. 找不同


下一篇:HDU OJ 2026