The Catalan numbers are a sequence of positive integers that appear in many problems of discrete mathematics, such as counting the number of ways to parenthesize an expression, or the number of full binary trees with n internal nodes. The nth Catalan number can be computed recursively using the formula C(n) = C(0)C(n-1) + C(1)C(n-2) + ... + C(n-1)C(0)
. Here's how you can use dynamic programming and memoization to implement a Ruby program that computes the nth Catalan number efficiently:
main.rb584 chars28 lines
This program uses a memoization table $catalan
to store the Catalan numbers computed so far. The catalan(n)
function first checks if the nth Catalan number has already been computed and stored in the memoization table, and if so, returns it. Otherwise, it uses the recursive formula to compute the nth Catalan number by summing up the products of each pair of Catalan numbers from C(0)
to C(n-1)
. Finally, it stores the result in the memoization table and returns it.
gistlibby LogSnag