Test instructions: A bracket string is given to find the shortest bracket string that satisfies the requirement;
Idea: Enumerate length, enumerate start and end points, find matching parentheses are recursive to sub-sequences, enumerate intermediate pointers for optimal solution, and the shortest sequence can be obtained recursively by memory table path storage optimal solution during printing;
#include <cstdio>#include<cstring>#include<algorithm>#defineINF 0x7fffffffusing namespacestd;Charstr[505];intdp[505][505];intpath[505][505];voidOprint (intIintj) { if(I>J)return; if(i==j) {if(str[i]=='['|| str[i]==']') printf ("[]"); Elseprintf"()"); } Else if(path[i][j]==-1) {printf ("%c", Str[i]); Oprint (i+1, J-1); printf ("%c", Str[j]); } Else{oprint (i,path[i][j]); Oprint (Path[i][j]+1, J); }}intMain () {gets (str); intn=strlen (str); if(n==0) {printf ("\ n");return 0; } memset (Path,0,sizeof(path)); Memset (DP,0,sizeof(DP)); for(intI=0; i<n;i++) Dp[i][i]=1; for(intR=1; r<=n;r++)//Recursive fader sequence length { for(intI=0; i<n-r;i++)//enumeration starting point { intJ=i+r;//calculates the end position of a sub-sequencedp[i][j]=0x7fffffff; if((str[i]=='('&&str[j]==')')|| (str[i]=='['&&str[j]==']') ) {Dp[i][j]=dp[i+1][j-1]; } Path[i][j]=-1;//put it on the outside, or WA for(intk=i;k<j;k++)//Enumerate intermediate pointers { if(dp[i][j]>dp[i][k]+dp[k+1][j]) {Dp[i][j]=dp[i][k]+dp[k+1][j]; PATH[I][J]=K; } }}} oprint (0, N-1); printf ("\ n"); return 0;}
POJ 1141 Brackets Sequence (linear DP)