Counting boolean parenthesizations
The parenthesization or counting boolean parenthesization problem is somewhat similar to optimal binary search tree finding. Given a boolean expression like
\[true \lor true \land false \oplus true\]the task is to determine the number of possible parenthesizations which render the expression \( true \). In the example above we have four solutions
\[true \lor ((true \land false) \oplus true) \\ true \lor (true \land (false \oplus true)) \\ (true \lor true) \land (false \oplus true) \\ ((true \lor true) \land false) \oplus true \\\]and only one way to render it \( false \)
\[(true \lor (true \land false)) \oplus true\]Let \( T(i,j) \) represent the number of ways to parenthesize the operands in the range \( [i;j] \) such that the subexpression evaluates to \( true \) and let \( F(i,j) \) be the number of ways it evaluates to \( false \). It follows that
\[T(i,j) = \begin{cases} \mbox{if operator is $\land$} \\[1pt] T(i,j) = T(i,k) \cdot T(k + 1,j) \\[2ex] \mbox{if operator is $\lor$} \\[1pt] T(i,j) = (T(i,k) + F(i,k)) \cdot (T(k + 1,j) + F(k + 1,j)) - (F(i,k) \cdot F(k + 1,j)) \\[2ex] \mbox{if operator is $\oplus $} \\[1pt] T(i,j) = (T(i,k) \cdot F(k + 1,j)) + (F(i,k) \cdot T(k + 1,j)) \\[2ex] \end{cases} \\\] \[F(i,j) = \begin{cases} \mbox{if operator is $\land$} \\[1pt] F(i,j) = (T(i,k) + F(i,k)) \cdot (T(k + 1, j) + F(k + 1, j)) - (T(i,k) \cdot T(k + 1, j)) \\[2ex] \mbox{if operator is $\lor$} \\[1pt] F(i,j) = F(i,k) \cdot F(k + 1, j) \\[2ex] \mbox{if operator is $\oplus $} \\[1pt] F(i,j) = (T(i,k) \cdot T(k + 1, j)) + (F(i,k) \cdot F(k + 1, j)) \\[2ex] \end{cases}\]The problem can be solved recursively or with a dynamic programming solution in \( O(N^3) \) as follows