I spent one day solving this problem and couldn\'t find a solution to pass the large dataset.
Problem
An n parentheses sequence consists of n \"(\"s and n \"
Let S= any valid sequence of parentheses from n( and n)
.
Now any valid sequence S can be written as S=X+Y
where
X=valid prefix
i.e. if traversing X from left to right , at any point of time, numberof'(' >= numberof')'
Y=valid suffix
i.e. if traversing Y from right to left, at any point of time, numberof'(' <= numberof')'
For any S
many pairs of X
and Y
are possible.
For our example: ()(())
`()(())` =`empty_string + ()(())`
= `( + )(())`
= `() + (())`
= `()( + ())`
= `()(( + ))`
= `()(() + )`
= `()(()) + empty_string`
Note that when X=empty_string
, then number of valid S
from n(
and n)
= number of valid suffix Y
from n(
and n)
Now, Algorithm goes like this:
We will start with X= empty_string
and recursively grow X
until X=S
. At any point of time we have two options to grow X
, either append '(' or append ')'
Let dp[a][b]= number of valid suffixes using a '(' and b ')' given X
nop=num_open_parenthesis_left
ncp=num_closed_parenthesis_left
`calculate(nop,ncp)
{
if dp[nop][ncp] is not known
{
i1=calculate(nop-1,ncp); // Case 1: X= X + "("
i2=((nop=ncp, then after exhausting 1 ')' nop>ncp, therefore there can be no valid suffix*/
dp[nop][ncp]=i1+i2;
}
return dp[nop][ncp];
}`
Lets take example,n=3 i.e. 3 (
and 3 )
Now at the very start X=empty_string
, therefore
dp[3][3]
= number of valid sequence S
using 3(
and 3 )
= number of valid suffixes Y
from 3 (
and 3 )