Longest Common Subsequence II

题目
Given two sequence P and Q of numbers. The task is to find Longest Common Subsequence of two sequence if we are allowed to change at most k element in first sequence to any value.

Example
Given P = [8 ,3], Q = [1, 3], K = 1
Return 2

Given P = [1, 2, 3, 4, 5], Q = [5, 3, 1, 4, 2], K = 1
Return 3

答案

public class Solution {
    /**
     * @param P: an integer array P
     * @param Q: an integer array Q
     * @param k: the number of allowed changes
     * @return: the length of lca with at most k changes allowed.
     */
    public int longestCommonSubsequenceTwo(int[] P, int[] Q, int K) {
        // write your code here
        int m = P.length, n = Q.length;
        //System.out.println("m = " + Integer.toString(m) + " n = " + Integer.toString(n));
        // f[i][j][k]: LCS(P[0...i-1], Q[0...j-1], k)
        int[][][] f = new int[m + 1][n + 1][K + 1];

        for(int i = 0; i <= m; i++) {
            for(int j = 0; j <= n; j++) {
                for(int k = 0; k <= K; k++) {
                    // LCS of any string with empty string is 0
                    if(i == 0 || j == 0) {
                        //System.out.println("i = " + Integer.toString(i) + " j = " + Integer.toString(j) + " k = " + Integer.toString(k));
                        f[i][j][k] = 0;
                        continue;
                    }

                    if(P[i - 1] == Q[j - 1])
                        f[i][j][k] = 1 + f[i - 1][j - 1][k];
                    else {
                        f[i][j][k] = Math.max(f[i][j - 1][k], f[i - 1][j][k]);
                        if(k > 0)
                            f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - 1][k - 1] + 1);
                    }

                }

            }
        }
        return f[m][n][K];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 周五,全区第34个教师节表彰大会胜利召开。 我们作为观众参加了会议。 说句不太好听的话,这样的表彰,真得是“年年岁...
    风雨同舟_f997阅读 115评论 0 0
  • 大雪时节无大雪,冷风刺骨飞鸟绝,疾风劲草寒更切。 云卷云舒皆风景,任由西风冷楼阙,润笔蘸墨酿岁月。
    恩玲阅读 274评论 0 0