Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【算法系列】fib优化 #49

Closed
AwesomeDevin opened this issue Apr 21, 2021 · 0 comments
Closed

【算法系列】fib优化 #49

AwesomeDevin opened this issue Apr 21, 2021 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

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
      }
  }
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant