Here's a Go function that finds the nth Catalan number using dynamic programming:
main.go370 chars15 lines
This function uses the fact that the nth Catalan number can be computed using the formula Cn = (2n)! / ((n+1)! * n!)
, which can also be expressed recursively as Cn = sum(Ci * Cn-i-1) for i in [0, n-1]
. However, using dynamic programming is more efficient than recursion for larger values of n.
The function initializes a slice of length n+1 to store previously calculated Catalan numbers. It then fills the slice using nested loops, computing each Catalan number by summing the products of two previously computed Catalan numbers. It finally returns the nth Catalan number.
gistlibby LogSnag