C++ Memoization understanding

前端 未结 3 1881
忘了有多久
忘了有多久 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:54

    What you are saying is essentially correct.

    "Does it [fibHash] just hold the individual values of each fib(#)?"

    Yes, exactly. The values are filled in as they are calculated (with fibHash[ n ] = fib_val;). Lower fib values are used to calculate the higher ones.

    The fibHash map maps X to fib(X), plain and simple.

    The advantage of doing it this way is that if you calculate fib(20) followed by fib(21) and fib(23), then perhaps fib(15), you only have to calculate the intermediate values once.

    The cost for this speedup is the memory of storing the values in fibHash.

提交回复
热议问题