记忆化递归和递推

记忆化递归

  • 记忆化是一种保存前一个结果的值的优化技术,类似于缓存。
function fibonacciMemoization(order) {
    const arr = [0, 1, 1]

    const fibonacci = (n) => {
        if (arr[n] === undefined) {
            arr.push(fibonacci(n - 1) + fibonacci(n - 2))
        }

        return arr[n]
    }

    return fibonacci(order)
}

普通递归

function fibonacci(n) {
    if (n <= 0) return 0
    if (n < 2) return n

    return fibonacci(n - 1) + fibonacci(n - 2)
}

递推

function fib(order) {
    if (order === 0 || order === 1) { return order }
   
    let prev = 0
    let curr = 1

    for (let index = 2; index <= order; index++) {
        [prev, curr] = [curr, prev + curr]
    }

    return curr
}
posted @ 2020-02-15 12:33  _Jarrett  阅读(233)  评论(0编辑  收藏  举报