front-end-pigs / blog

博客
2 stars 0 forks source link

斐波那契函数优化 #25

Open jangdelong opened 4 years ago

jangdelong commented 4 years ago

优化前:

const fib = n => {
  if (n === 0 || n === 1) {
    return n
  }
  return fib(n - 1) + fib(n - 2)
}

优化后:

使用闭包进行记忆化优化。

const fib = (function (n) {
  const f = {}
  return function (n) {
    if (n === 0 || n === 1) {
      return n
    }
    if (f[n - 1] === undefined) {
      f[n - 1] = fib(n - 1)
    }
    if (f[n - 2] === undefined) {
      f[n - 2] = fib(n - 2)
    }

    return f[n] = f[n - 1] + f[n - 2]
  }
})()
pwcong commented 3 years ago

尾调用优化:

function fib(n, a = 1, b = 0) {
  if (n === 0) {
    return 0;
  }

  if (n === 1) {
    return a;
  }

  return fib(n - 1, a + b, a);
}