算法笔记8:最长公共子序列

128 阅读1分钟

1143.最长公共子序列

解法来自 mp.weixin.qq.com/s/ZhPEchewf…

这道题目总结一下也是动态规划那几步:

  1. 找边界条件
  2. 找决策的分枝
  3. memo 优化
const longestCommonSubsequence = (text1, text2) => {
    const memo = Array(text1.length)
        .fill(null)
        .map(() => Array(text2.length));
    const dp = (t1, i, t2, j) => {
        // i and j reach the end
        if (i === t1.length || j === t2.length) {
            return 0;
        }

        if (memo[i][j] !== undefined) {
            return memo[i][j];
        }

        if (t1[i] === t2[j]) {
            // i and j both move forward
            memo[i][j] = 1 + dp(t1, i + 1, t2, j + 1);
        } else {
            // either i move forward or j move forward
            memo[i][j] = Math.max(
                dp(t1, i + 1, t2, j),
                dp(t1, i, t2, j + 1)
            );
        }

        return memo[i][j];
    }
    return dp(text1, 0, text2, 0);
};

题外话,感觉 DP 题目确实需要多见题型才能抓到感觉,这个无它,唯手熟尔。