0

For given n find the number of valid combinations of valid parenthesis.I told him direct formula of Catalan number(becuase i encountered this prob earlier) but he specifically wanted this problem Solution using dynamic programming and wanted working solution with explanation with Test cases.I didn't managed to get to the working solution.

Eg:

n=1 valid par=0

n=2 valid par=1

Now I just want to understand this problem

I found one explanation but not getting it Please can you help me in understanding or can you provide more verbose explanation of below logic (which seems to be correct)

You need even number of paranthesis, if C(n) denotes the number of valid paranthesis with 2 * n paranthesis then

C(0)=1 and for any n>0

C(n)=C(0) * C(n-1)+C(1) * C(n-2)+...+C(n-1) * C(0)=sum(i=0,n-1,C(i) * C(n-1-i))

because you need to start with a '(' and see where is that closing bracket with a ')' if there is 2 * i paranthesis between them then the number of such cases is C(i) * C(n-1-i).

user10891599
  • 41
  • 1
  • 5

2 Answers2

1

Recursion is the key here.

Divide the N into N/2 and N/2 (Count for open and closed parentheses ).

Select the open parentheses, add it to the result string, and reduce its count and make a recursive call.

Select the close parentheses, add it to the result string, and reduce its count and make a recursive call.

To print only valid parentheses, make sure at any given point of time, close parentheses count is not less than open parentheses count because it means close parentheses have been printed with its respective open parentheses.

Take a look at this link.

Yash Shah
  • 1,634
  • 1
  • 5
  • 16
1

M[i][j] dp state. The length between i - j is always even number.

Then problem is similar to matrix multiplication.

M[i][j] = M[i][i+1]*M[i+2][j] + M[i][i+3]*M[i+4][j] + ..... + M[i][j-2]*M[j-1][j]

Also add the case where i'th parentheses is '(' and j'th parentheses is ')'

M[i][j] += M[i+1][j-1]

Ashish Khurange
  • 903
  • 7
  • 17