Test instructions: The string s with a length of less than 100 are composed of only four characters "() []", which is the shortest legal string of the substring. The legal string recursion is defined as:
(1) empty string legal
(2) If S is legal, then (s), [s] Legal
(3) If a, B is legal, then AB legal
Ideas:
Set DP[I][J] for S (i,j) to become legal strings, the length of the legal string or the number of characters that need to be added, State transfer:
(1) if s[i] and S[j] match, Dp[i,j]=dp[i+1,j-1].
(2) If not, divide S (i,j) to S (i,k) and S (k+1,j), divide dp[i,j]=dp[i,k]+dp[k+1,j], if two substrings match the maximum number of parentheses, then you need to add the fewest characters, that is, dp[i,k+1]+dp[k+1, J] min, k similar to segment point, S (i,k) and S (k+1,j) can be output separately, so Dp[i,j]=min (Dp[i,k]+dp[k+1,j])
Dependency Relationship:
Seek Dp[i,j] first to seek [I,k][k,j], that is, the large interval depends on the inter-cell, so the interval length from the beginning of the smallest traversal. To traverse all the inter-community, start at the beginning of 0. So there are
For
2 to n
For
0 to n-
1
状态转移,遍历
k
Initial state:
Dp[i][i] must match one character, so dp[i,i]=1
Output
If you know which of S is not matched in S, add a match next to the character. S[I,J] Need dp[i,j] characters to match, discuss the situation:
If i>j, the illegal interval
If I==j, a single character, directly outputs the corresponding "()" or "[]"
If i<j, legal intervals, sub-conditions
If S[i] and S[j] match, just look at S (i+1,j-1), recursive output outputs (s[i]); Output (i+1,j-1); Output (j);
If the s[i] and s[j] matches do not match, the segment Point K is unique in dp[i,k] when the state transitions, (i,k) and (K+1,J) are independent, so you can record K with a pos[i,j], and then segment the output, that is, outputs (I,K); Output (K+1,J)
Algorithm steps:
Step 1: Initialize dp[][] to infinity, dp[i][i]=1,pos=-1.
Step 2: Recursive dp[i][j], then output a new string recursively according to the POS.
Code:
intdp[ the][ the],pos[ the][ the];voidDfsprint (intLintR//Path Output{ if(L>r)return ; if(l==R) { if(s[l]=='('|| s[l]==')') cout <<"()" ; Elsecout <<"[]" ; } Else if(pos[l][r]==-1) {cout<< S[l]; Dfsprint (L +1, R-1); cout <<S[r]; } Else{dfsprint (l,pos[l][r]); Dfsprint (Pos[l][r]+1, R); }}intMain () {CIN>>s; memset (Dp,inf,sizeof(DP)); memset (POS,-1,sizeof(POS));intLen =s.size (); for(intI=0; i<len;++i) dp[i][i]=1, dp[i+1][i]=0; for(intLength=1; length<len; ++lenght) { for(intstart=0; start+length<len; ++start) {Dp[i][j]=len+1;//Max//S[i] s[j] Matchif((s[i]=='('&&s[j]==')') || (s[i]=='['&&s[j]==']')) Dp[i][j]=min (Dp[i][j], dp[i+1][j-1]); //State Transitions for(intk=i;k<j;++k) { 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; } }}} dfsprint (0, len-1); cout<<Endl; return 0;}
URAL 1183 Brackets Sequence DP path output