Advertisement
bero_0401

Catalan numbers

Jul 13th, 2024 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | Source Code | 0 0
  1. def catalan_number_dp(n):
  2.     # Create a list to store results of subproblems
  3.     catalan = [0] * (n + 1)
  4.    
  5.     # Base case
  6.     catalan[0] = 1
  7.    
  8.     # Fill the entries in a bottom-up manner
  9.     for i in range(1, n + 1):
  10.         for j in range(i):
  11.             catalan[i] += catalan[j] * catalan[i - j - 1]
  12.    
  13.     return catalan[n]
  14.  
  15. # Test the function
  16. for i in range(10):
  17.     print(f"C_{i} = {catalan_number_dp(i)}")
  18. # Cn valid parenthesis expressions
  19. # Cn binary trees of n nodes
  20. # Cn−1 rooted trees of n nodes
  21. #  there are n**(n−2) labeled trees that contain n nodes.
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement