How to initialize Multi-Dimensional cache in TS

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 of melements, each initially null.

  • .map(() => Array(n).fill(null))replaces each nullwith a ​​new array​​ of size nfilled with null. 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 column jin ​​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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值