- Given a sequence a1,a2,…,an of n numbers separated by n−1 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:
- P(1)=1
- P(2)=1
- P(3)=2
- (a1(a2a3))
- ((a1a2)a3)
- P(4)=5
- (a1(a2(a3a4)))
- (a1((a2a3)a4))
- ((a1a2)(a3a4))
- ((a1(a2a3))a4)
- (((a1a2)a3)a4)
- Recursive Formula:
- P(n)=i=1∑n−1P(i)P(n−i)
- Where i splits the sequence into a left part with i elements and a right part with n−i elements
- Base cases: P(1)=P(2)=1
- Dynamic Programming Optimization:
- Use an array
dp
to store results for subproblems
- Initialize
dp[1]=dp[2]=1