JavaScript Fibonacci breakdown

前端 未结 3 659
故里飘歌
故里飘歌 2020-12-10 18:31

I hope it is ok that I am posting this question here even though I have also posted it on other sites. If I have failed to follow proper protocols, I apologize and please l

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 18:55

    I know the question is a bit old, and the answers are helpful. I was doing this exercise in GoLang, and thought how I would write in Javascript, and use this answer to refresh my mind as well. I see your code has a cache variable to store the value of the fib(n-2) + fib(n-1) iteration. If you're doing recursive, you don't need a variable to store the result, because each time the function is called it returns a number, and these numbers are added up to the first function call.

    function fib(n) {
        if (n<=1) return n;
        return fib(n - 1) + fib(n - 2);
    }
    

    To see why you don't need the cache variable is go through each function call, and start calculate the values once n equal 1 or 0.

    for example:

    iteration 1)
    
    fib(3) {
       return fib(3-1) + f(3-2)   
    }
    ---------------------------    
    iteration 2)
    
    fib(3-1) {
       return fib(2 - 1) + fib(2-2)
    }
    
    iteration 3)
    
    fib(3-2) {
       return 1
    }    
    ---------------------------
    
    iteration 4)
    
    fib(2-1) {
       return 1
    }
    
    
    iteration 5)
    fib(2-2) {
       return 0
    }
    ----------------------
    

    if you calculate it the return value backward from iteration 5)

    5) 0
    4) 1
    3) 1
    2) 1 <== 4) + 5)  = 1 + 0  
    1) 2  <== 2) + 3)  = 1 + 1
    

    so fib(3) is 2

提交回复
热议问题