Memoization pascals triangle

后端 未结 3 928
春和景丽
春和景丽 2020-12-20 07:55

I\'m not interested in the actual solution or other methods solving the problem, it\'s the memoization i need help with :)

I need help doing a pascals triangle probl

3条回答
  •  无人及你
    2020-12-20 08:26

    Memoization doesn't work in your functions because a call like memopascals 5 5 builds internally a part of the triangle and returns a single value from it. A different call mempascals 6 6 doesn't have any connection to that partial triangle internal to memopascals 5 5.

    For efficient memoization you want the common part (like the list of lists that represents the calculated numbers in the triangle) in a separate function, which is then used by the functions that access specific indexes. This way you use the same list of lists to lookup different indexes.

    Usually the easiest way to do this is to write one function like fullpascals :: [[Int]] that produces the complete (infinite) data structure, and than another function to access that data structure, like

    memopascals x y = fullpascals !! (x-1) !! (y-1)
    

    In your case fullpascals would be the same as one of your current functions, but without the parameters for a specific index. It can even still use memopascals internally for the recursion.


    Sidenote: In the memoized_fib example in the wiki, the "common part" that is memoized isn't directly the list of all fibs, but a function that accesses the list of all fibs. The effect is the same, since the compiler is smart enough to optimize this.

提交回复
热议问题