Given a string S, in one move it is allowed to remove two adjacent equal characters. After the removal, both endpoints of the removed characters are joined. Calculate the total number of ways to empty the string.
Example:
Input: S = aabccb
Output: 3
Explanation:
1. aabb -> aa ->
2. aabb -> bb ->
3. bccb -> bb ->
Hence, there are a total of 3 ways to empty the string after a valid set of moves.
Input: S = aabbc
Output: 0
Explanation: The string is of odd length, so it is not possible to empty the whole string.
Approach: The above problem can be solved with the help of Dynamic Programming. Follow the steps below to solve the problem:
- Let's define a 2-d dp table dp[i][j] which will store the answer for the range [i, j].
- Define a recursive approach to solve the problem.
- To calculate dp[i][j], loop through all indices k between i and j where S[i] = S[k].
- Now for an individual k, the answer would be dp[i+1][k-1]*dp[k+1][j]*(Total number of ways to arrange the removals of the range).
- To calculate the last term of the equation, notice that the removal of the whole range [i+1, k-1] will take place before the removal of S[i] and S[k].
- So the total removals in the range will be (j - i + 1)/2 (since two elements are removed at a single time). From these removals have to choose (j - k)/2 removals.
- So the final formula will be
- Use to not recalculate the states again.
- Check for the bases cases in the recursive function.
- The final answer will be dp[0][N-1]
Below is the implementation of the above approach:
Time Complexity: O(N^3)
Auxiliary Space: O(N^2)