简体   繁体   中英

How do I calculate binomial coefficient with memoization?

The recursive form is like that:

co:: (Int,Int) -> Int
co| k == 0 || k == n = 1
  | 0 < k, k < n = co(n-1,k-1) + co(n-1,k)
  | otherwise = 0

How do I memorize so I don't have to make the same calculations that often?

Here's how to implement binomial coefficients if you are feeling sane and want someone to understand your program:

--| computes the binomial coefficient n choose k = n!/k!(n-k)!
binom n k = product [max (k+1) (n-k+1) .. n] `div` product [1 .. min k (n-k)]

Here is a simple way to memoize a function of two arguments like this:

binom n k = (vals !! n) !! k where
  vals = 1 : [ 1 : [if k == n
                    then 1
                    else binom (n-1) (k-1) + binom (n-1) k
                   | k <- [1..n]]
             | n <- [1..]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM