###### tags:`Function` | `leetCode` <font color="#01AE9A" background="E1F3F0">`easy`</font> ### 題目 Given a function fn, return a memoized version of that function. A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. You can assume there are 3 possible input functions: sum, fib, and factorial. sum accepts two integers a and b and returns a + b. fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise. factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise. ### Example ```javascript= Input "sum" ["call","call","getCallCount","call","getCallCount"] [[2,2],[2,2],[],[1,2],[]] Output [4,4,1,3,2] Explanation const sum = (a, b) => a + b; const memoizedSum = memoize(sum); memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before. memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before. // Total call count: 1 memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before. // Total call count: 2 ``` --- ### 解題邏輯 這題光是題目就有點難理解了~基本上就是寫一個會記憶的 memoize fn,如果傳給他[2,2],他會return 2+2=4,如果再傳入一樣的[2,2],則要回傳剛剛存起來的結果而不是重新計算一次 ```javascript= let callCount = 0; const memoizedFn = memoize(function (a, b) { callCount += 1; return a + b; }) memoizedFn(2, 3) // 5 memoizedFn(2, 3) // 5 console.log(callCount) // 1 ``` ```javascript= function memoize(fn) { const cache = {} // 設一個 cache 的空物件 return function(...args) { const key = JSON.stringify(args) // 把傳進來的參數轉為字串(因為如果比對[2,2]===[2,2],因為兩個 arr 所存的記憶體不同所以會回傳 false) if(key in cache){ // 如果 cache 中有一樣的 key 了就直接回傳 cache[key] return cache[key] } const output = fn(...args) // 把 output 指定給 cache 裡的 key cache[key] = output return output } } ```