As before, be aware of the enumeration order of States, the boundary is d[i+1][i] = 0 and D[i][i] = 1, so the interval of the enumeration should be small to large, the large interval depends on the optimal solution between the cells.
Then there is the transfer of state, how is it transferred? D[I][J] represents the optimal solution of the string i~j, first check if I and J match, if the match, the state transfer can be transferred to D[i+1][j-1]. Regardless of whether the match, the state can also be transferred to the sub-range: D[i][k] and d[k+1][j], this is not like the optimal matrix chain multiplication problem? It's just that the formal bracket sequence is defined by the question: if S is a regular bracket sequence, then (s) and [s] are also regular brackets, so there is the extra DP.
The difficulty of the problem also lies in the solution printing and the input and output of the format control (empty sequence trap). See the code for details:
#include <bits/stdc++.h>using namespace Std;const int maxn = 109;int t,n,d[maxn][maxn];string s;bool match (Char A, Char b) {if ((a== ' (' &&b== ') ') | | (a== ' [' &&b== ']) return true; else return false;} void print (int i,int j) {if (i > J) return; if (i = = j) {if (s[i] = = ' (' | | s[i] = = ') ') printf ("()");//informal sequence, supplemented with normal sequence else printf ("[]"); return; } int ans = d[i][j]; if (Match (s[i],s[j) && ans = = D[i+1][j-1]) {//ans = = D[i+1][j-1] This condition is extremely important, only to satisfy this, can it be explained that the sub-optimal solution of its dependence is what printf ("% C ", S[i]); Print (i+1,j-1); printf ("%c", S[j]); return; } for (int k=i;k<j;k++) {if (ans = = D[i][k] + d[k+1][j]) {//step-back search for the sub-optimal solution print (I,K) on which the optimal solution depends; print ( K+1,J); return; }}}int Main () {scanf ("%d", &t); int c = GetChar (); c = GetChar (); while (t--) {getline (cin,s); n = s.size (); if (n = = 0); else {for (int i=0;i<n;i++) {D[i][i] = 1; D[i+1][i] = 0; } for (int i=n-2;i>=0;i--) {for (int j=i+1;j<n;j++) {D[i][j] = n; if (Match (S[i],s[j])) d[i][j] = min (d[i][j],d[i+1][j-1]); for (int k=i;k<j;k++) d[i][j] = min (d[i][j],d[i][k]+d[k+1][j]); }} print (0,n-1); } printf ("\ n"); Format control if (T) printf ("\ n"); if (T) c = GetChar (); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
1626-brackets sequence (DP)