The issue lies in how the 2D cache array is initialized. The original code uses:
const cache = Array(m).fill(Array(n).fill(null));
This creates an array with melements, but each element references the same inner array due to Array(n).fill(null)being evaluated once and shared across all rows. When you update cache[i][j], it affects all rows because they share the same array.
Solution: Initialize the cache with distinct arrays for each row:
const cache = Array(m).fill(null).map(() => Array(n).fill(null));
Explanation:
-
Array(m).fill(null)creates an array ofmelements, each initiallynull. -
.map(() => Array(n).fill(null))replaces eachnullwith a new array of sizenfilled withnull. This ensures each row is a separate array.
Corrected Code:
function minDistance(word1: string, word2: string): number {
const m = word1.length;
const n = word2.length;
const cache = Array(m).fill(null).map(() => Array(n).fill(null)); // Fixed initialization
function dfs(i, j) {
if (i < 0 || j < 0) { return i < 0 ? j + 1 : i + 1 }
if (cache[i][j] !== null) { return cache[i][j] }
let res;
if (word1[i] === word2[j]) {
res = dfs(i - 1, j - 1);
}
else {
res = Math.min(
dfs(i - 1, j - 1),
dfs(i - 1, j),
dfs(i, j - 1),
) + 1;
}
cache[i][j] = res;
return res;
}
return dfs(m - 1, n - 1);
};
Why the original fails:
-
All rows in
cachepoint to the same array. -
Updating
cache[i][j]overwrites values for the same columnjin all rows. -
Subsequent accesses to
cache[i][j]return incorrect memoized values, leading to wrong results.
The fix ensures each row is independent, preserving correct memoization.
3224

被折叠的 条评论
为什么被折叠?



