js缓存函数

function memoize(fn) {
    const cache = new Map();  // 使用 Map 来存储缓存结果

    return function(...args) {
        // 将参数转换为字符串作为键
        const key = JSON.stringify(args);
        
        // 如果缓存中存在该键,则直接返回缓存的结果
        if (cache.has(key)) {
            return cache.get(key);
        }

        // 否则,调用原始函数并存储结果
        const result = fn.apply(this, args);
        cache.set(key, result);

        return result;
    };
}
// 示例:使用 memoize 函数来缓存组合数计算
function combinationSum4(nums, target) {
    const dfs = memoize(function(remaining) {
        if (remaining === 0) {
            return 1;
        }
        let result = 0;
        for (let x of nums) {
            if (x <= remaining) {
                result += dfs(remaining - x);
            }
        }
        return result;
    });

    return dfs(target);
}

// 测试代码
const nums = [1, 2, 3];
const target = 4;
console.log(combinationSum4(nums, target));  // 输出组合数

posted @ 2024-11-28 15:21  Jikefan  阅读(18)  评论(0)    收藏  举报