AwesomeDevin / blog

Welcome to Devin's blog,I'm trying to be a fullstack developer and sticking with it !!!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

【算法系列】fib优化

AwesomeDevin opened this issue · comments

fib性能不好主要是因为会多次计算重复n,因此需要对n的计算结果进行缓存

const fn = (() => {
  const obj = {}
  // obj变量形成闭包,用于缓存fn(n)
  return function(n){
    if(obj[n]) return obj[n] 
    if(n===1) return 0
      else if(n===2) return 1
      else {
        res = fn(n-1) + fn(n-2)
        obj[n] = res
        return res
      }
  }
})()