【问题标题】:How can i reduce the time of execution of this code如何减少此代码的执行时间
【发布时间】:2021-12-02 01:07:50
【问题描述】:
var yourself = {
    fibonacci : function(n) {
        return n === 0 ? 0 : n === 1 ? 1 : 
        this.fibonacci(n -1) + this.fibonacci (n-2)
    }
};

这个函数不断地设置它的'fibonacci'属性的值,基于 为函数的“n”参数提供的参数。 我想重构函数以减少执行时间

【问题讨论】:

    标签: javascript dynamic-programming fibonacci memoization


    【解决方案1】:

    使用动态规划,缓存已计算结果的记忆

    在此处阅读有关memoization 的更多信息

    const memoFib = function () {
        let memo = {}
        return function fib(n) {
            if (n in memo) { return memo[n] }
            else {
                if (n <= 1) { memo[n] = n }
                else { memo[n] = fib(n - 1) + fib(n - 2) }
                return memo[n]
            }
        }
    }
    
    const fib = memoFib()
    console.log(fib(50));
    

    【讨论】:

      【解决方案2】:

      您可以实现某种缓存。这样您就不需要多次重新计算相同的结果。

      var yourself = {
          fibonacci : function(n, cache = new Map()) {
              if(cache.has(n)) return cache.get(n);
              if(n === 0) return 0;
              if(n === 1) return 1;
              
              const start = this.fibonacci(n-1, cache);
              const end = this.fibonacci(n-2, cache);
              
              cache.set(n-1, start);
              cache.set(n-2, end);
              
              return start + end;
          }
      };
      
      console.log(yourself.fibonacci(40));

      【讨论】:

      • 谢谢@Reyno。这可以解决问题,我必须阅读内存缓存。你有这方面的参考吗?
      猜你喜欢
      • 1970-01-01
      • 2019-12-14
      • 2016-07-24
      • 1970-01-01
      • 2011-04-08
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多