C++ Memoization understanding

前端 未结 3 1879
忘了有多久
忘了有多久 2020-12-22 02:01

I was trying to understand how memoization works in C++, so I looked at an example of memoization used in Fib. sequence.

std::map fibHash;

         


        
3条回答
  •  感情败类
    2020-12-22 02:34

    Does it just hold the individual values of each fib(#)?

    Yes.

    Also, the iterator traversess through the index to look for the correct value in the table and returns that?

    Yes.

    For example fib(6) = find fib(5) and fib(4), already stored and just add them?

    Depends. First fib(6) searches to see if fib(6) has been called before. If it has then the stored answer gets returned. If it has never been called then fib(5) and fib(4) are called. The interesting thing is that if fib(5) has to be calculated it calls fib(4) before fib(6) does*, and then when fib(6) also calls fib(4) the result is guaranteed to found in fibHash because fib(5) already called fib(4). This is what causes the collapse of fib(n) from exponential time into something more like linear.

    The naive recursive implementation of Fibonacci boils down to adding 1 together many times.

    fib(5) =
    fib(4)                                     + fib(3) =
    fib(3)                   + fib(2)          + fib(2)          + fib(1) =
    fib(2)          + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + fib(1) =
    fib(1) + fib(0) + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + fib(1) = 
    1      + 1      + 1      + 1      + 1      + 1      + 1      + 1 =
    8
    

    In fact, to calculate fib(n) you end up doing fib(n)-1 additions. But if in the course of calculating fib(n) you save and use previously calculated Fibonacci numbers then you no longer have to perform so many additions. To calculate fib(n) this way only requires n additions:

    fib(5) =
    fib(4)                            + fib(3) =
    fib(3)                   + fib(2) + fib(3) =
    fib(2)          + fib(1) + fib(2) + fib(3) =
    fib(1) + fib(0) + fib(1) + fib(2) + fib(3) = 
    1      + 1      + 1      + 2      + 3 =
    8
    

    * Although the order isn't guaranteed. fib(6) may call fib(4) first, and then when fib(6) calls fib(5) fib(5) calls fib(4) which is now guaranteed to return a stored value.

提交回复
热议问题