Rule sequence: If S is a rule sequence, [s] Or (s) is also a rule sequence. If a and B are both rule sequences, AB is a rule sequence. Returns a string containing parentheses "()" and square brackets "[]".
Find the sequence of rules with minimum parentheses and print them out.
Idea: contains the replay problem and the DP of the recursion motivation.
In the string, WW [I] = '(' & WW [J] = ') 'or WW [I] =' ['& WW [J] ='] ', then obviously you only need to look at the results of DP [I + 1] [J-1.
DP [I] [J] = min (DP [I] [k] + dp [k + 1] [J]), I <= k <J;
Then, we can find the minimum K in the center for DP [I] [J] and record it to facilitate recursive printing of the Rule sequence.
AC program:
# Include <iostream> # include <stdio. h> # include <string. h> using namespace STD; # define INF 1000000000 char WW [108]; int DP [108] [108]; int POS [108] [108]; // DP [I] [J] indicate: the characters from I to J // the smallest length added. void print (int A, int B) {// cout <A <"" <B <Endl; if (a = B) {If (WW [a] = '(' | WW [a] = ') {// lost the last half printf ("()");} else {printf ("[]") ;}} if (a >= B) {return ;}// can't set a flag cause all leaves shoshould be printed. if (Pos [a] [B] =-1) {If (WW [a] = '(') {printf ("("); print (a + 1, B-1); printf (")");} else {printf ("["); print (a + 1, B-1 ); printf ("]") ;}} else {print (A, POS [a] [B]); print (Pos [a] [B] + 1, b) ;}} int main () {scanf ("% s", WW + 1); int n = strlen (WW + 1 ); // from 1 to startfor (INT I = 1; I <= N; I ++) {for (Int J = 1; j <= N; j ++) {DP [I] [J] = inf;} DP [I] [I-1] = 0; DP [I] [I] = 1;} memset (Pos,-1, sizeof (POS); For (INT p = 1; P <= n-1; P ++) {for (INT I = 1; I <= N-P; I ++) {Int J = I + P; If (WW [I] = '(' & WW [J] = ')') | (WW [I] = '[' & WW [J] = ']') {// DP [I] [J] = min (DP [I] [J], DP [I + 1] [J-1]); if (DP [I] [J]> DP [I + 1] [J-1]) {DP [I] [J] = DP [I + 1] [J-1]; pos [I] [J] =-1 ;}} for (int K = I; k <= J-1; k ++) {// DP [I] [J] = min (DP [I] [J], DP [I] [k] + dp [k + 1] [J]); if (DP [I] [J]> DP [I] [k] + dp [k + 1] [J]) {DP [I] [J] = DP [I] [k] + dp [k + 1] [J]; pos [I] [J] = K ;}}} print (1, N); printf ("\ n "); // cout <POS [1] [N] <Endl; // printf ("% d \ n", DP [1] [N]); // system ("pause"); Return 0 ;}