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];
    }
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評論 0 10
  • 周五,全區(qū)第34個教師節(jié)表彰大會勝利召開。 我們作為觀眾參加了會議。 說句不太好聽的話,這樣的表彰,真得是“年年歲...
    風雨同舟_f997閱讀 140評論 0 0
  • 大雪時節(jié)無大雪,冷風刺骨飛鳥絕,疾風勁草寒更切。 云卷云舒皆風景,任由西風冷樓闕,潤筆蘸墨釀歲月。
    恩玲閱讀 311評論 0 0

友情鏈接更多精彩內容