• Given a sequence of numbers separated by binary operators
  • Goal: Count all possible valid ways to parenthesize the sequence, foucsing on the order of operations but not the actual values of the numbers
  • Example:
  • Recursive Formula:
      • Where splits the sequence into a left part with elements and a right part with elements
    • Base cases:
  • Dynamic Programming Optimization:
    • Use an array dp to store results for subproblems
    • Initialize dp[1]=dp[2]=1
def count_parentheses(n):
    # Base cases
    if n <= 2:
        return 1
    
    # Initialize a table to store results for subproblems
    dp = [0] * (n + 1)
    dp[1] = 1
    dp[2] = 1
    
    # Fill the table iteratively
    for m in range(3, n + 1):
        for i in range(1, m):  # Split into two parts
            dp[m] += dp[i] * dp[m - i]
    
    return dp[n]