Problem in question

hello. if i am given input as

6 2

((

then the possible combinations should be ((())) (()()) (())() ()(()) right?

yes there are 4 possible answers for this

I am not able to think of a solution to solve this. Can you please give some hint

sir please reply .

you have to use dp to solve this problem

check out this
Reference Code

Iā€™m not able to understand what is done in the code. Moreover why is 3d dp used?

anyone? .

Approach

  1. It is quite obvious that we would only add opening brackets ā€˜(ā€™ to string A and only closing brackets ā€˜)ā€™ to string B

  2. Since the number of open and close brackets must be equal, we can never generate a valid string if n is odd.

  3. Count the total number of opening and closing brackets required to balanced the string. The opening brackets will go in string A and the closing brackets will go in string B.

  4. We start from pos = 0 and go till pos = n - m + 1. At each instance we consider three possibilities.

  5. if closingBrackets have not been implemented yet (close==0) and count of open brackets that we have implemented is more than required (open >= openBrackets) then, we implement the closing brackets required for string B and raise a flag for the same by marking close=1 also, change the open bracket count accordingly for this case

  6. if we have some open brackets then, put a closing bracket to balance it and decrease open count to denote there is one less unbalanced open bracket now

  7. add another opening bracket to the string so far. This bracket will be initially unbalanced.

  8. We add the results obtained from the three possibilities. We store and return this result.

  9. Continue the above process till pos < n-m+1.

  10. At pos == n-m+1, we must ensure that all required opening and closing brackets have been implemented. We do so by checking the status of out flag variable close i.e. check close==1. Also make sure there are no pending unbalanced open brackets (open==0).

why did we go only upto n-m+1?