Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

最长公共子序列

Sunny-117 opened this issue · comments

动态规划经典题目!

const LCS = function (strA, strB) {
    let dp = new Array(strA.length + 1).fill(0).map(item => new Array(strB.length + 1).fill(0));
    for (let i = 1; i <= strA.length; i++) {
        for (let j = 1; j <= strB.length; j++) {
            if (strA[i] === strB[j]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[strA.length][strB.length];
}