2630.记忆函数II
链接:2630.记忆函数II
难度:Hard
标签:
简介:请你编写一个函数,它接收一个函数参数 fn,并返回该函数的 记忆化 后的结果。
题解 1 - typescript
- 编辑时间:2023-04-23
- 执行用时:372ms
- 内存消耗:102MB
- 编程语言:typescript
- 解法介绍:trie。
type Fn = (...params: any) => any;
const EmptyResult = Symbol('EmptyResult');
class Trie {
  children = new Map<any, Trie>();
  result: any = EmptyResult;
  constructor(public val: any) {}
}
function memoize(fn: Fn): Fn {
  const root = new Trie(null);
  return function (...args: any[]) {
    let node = root;
    for (const arg of args) {
      let next = node.children.get(arg);
      if (!next) node.children.set(arg, (next = new Trie(arg)));
      node = next;
    }
    if (node.result !== EmptyResult) return node.result;
    return (node.result = fn(...args));
  };
}