Let S= any valid sequence of parentheses from n( and n) . Now any real sequence S can be written as S=X+Y , where
X=valid prefix i.e. if the intersection X is from left to right, at any given time, numberof'(' >= numberof')'Y=valid suffix i.e. if the intersection Y is from right to left, at any given time, numberof'(' <= numberof')'
For any S , many pairs of X and Y possible.
In our example: ()(())
`()(())` =`empty_string + ()(())` = `( + )(())` = `() + (())` = `()( + ())` = `()(( + ))` = `()(() + )` = `()(()) + empty_string`
Note that for X=empty_string number of valid S of n ( and n ) = the number of valid suffix Y of n ( and n )
Now the algorithm is as follows: We start with X= empty_string and grow X recursively to X=S At any given time, we have two options for growing X , either add '(' 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)?calculate(nop,ncp-1):0); /*Case 2: X=X+ ")" if nop>=ncp, then after exhausting 1 ')' nop>ncp, therefore there can be no valid suffix*/ dp[nop][ncp]=i1+i2; } return dp[nop][ncp]; }`
Take an example, n = 3, i.e. 3 ( and 3 ) Now at the very beginning X=empty_string , therefore
dp[3][3] = number of valid sequence S using 3 ( and 3 ) = number of valid suffixes Y of 3 ( and 3 )
source share