The sequence of regular parentheses is defined:
- The empty sequence is a sequence of regular parentheses.
- If S is a sequence of formal parentheses, [s] and (s) are also a sequence of formal parentheses.
- If both A and B are regular parentheses, AB is also a regular parenthesis sequence.
Enter a sequence of parentheses, add as few parentheses as possible to make them a sequence of formal parentheses, and output the optimal scheme. If there are multiple solutions, output any one.
Set d (I, j) to the string s [I] ~ The number of parentheses added at least in S [J] is transferred as follows:
- S form, such as [s '] Or (s'), is transferred to d (I + 1, J-1)
- If S contains at least two characters, it is divided into AB and transferred to min {d (I, j), D (A) + d (B )}
Try the second transfer regardless of whether the first transfer is met, because [] [] may go through the first transfer] [
Re-check the optimal decision when printing.
1 // # define local 2 # include 3 # include 4 # include 5 using namespace STD; 6 7 const int maxn = 110; 8 char s [maxn]; 9 int d [maxn] [maxn], n; 10 11 bool match (char a, char B) 12 {13 return (A = '(' & B = ') | (A =' ['& B ='] '); 14} 15 16 void dp () 17 {18 for (INT I = 0; I = 0; -- I) 24 {25 for (Int J = I + 1; j J) return; 39 if (I = J) 40 {41 if (s [I] = '(' | s [I] = ') printf ("()"); 42 else printf ("[]"); 43 return; 44} 45 int ans = d [I] [J]; 46 If (MATCH (s [I], s [J]) & Ans = d [I + 1] [J-1]) 47 {48 printf ("% C", s [I]); 49 print (I + 1, J-1); 50 printf ("% C", s [J]); 51 return; 52} 53 for (int K = I; kCode Jun
Ultraviolet A 1626 (output solution) Brackets Sequence