实现说明
最长公共子序列动态规划可以归结为函数 longestCommonSubseq。
核心工作在嵌套循环里完成:外层 for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++),内层 while (i > 0 && j > 0)。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 longestCommonSubseq。
主签名形如 function longestCommonSubseq(a: string, b: string)
核心语句
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
return result.join('');
代码示例
function longestCommonSubseq(a: string, b: string): string {
const m = a.length, n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
let i = m, j = n; const result: string[] = [];
while (i > 0 && j > 0) {
if (a[i - 1] === b[j - 1]) { result.unshift(a[i - 1]); i--; j--; }
else if (dp[i - 1][j] > dp[i][j - 1]) i--; else j--;
}
return result.join('');
}