This problem bothered me for a while, because I would only ask for the maximum match, will not print the path, and later found that it can be achieved by recursion, first we know that the previous definition of DP [i] [j] is the maximum number of matches from the first I to the J brackets in the string
So if we know where to insert points from any I to J, the match is added with the fewest parentheses. Then we define POS "I" "J" to indicate where I to j separates so that matches are added with the fewest parentheses, if I and J match we can let Pos "I" "J" =-1;
We found that before we update DP [i] [j] when the intermediate point K makes the IF (DP [i] [K] + DP [k+1] [j] >= DP [i] [j]), then we can separate the parentheses from the K to add the least, the most pit One thing is there may be empty string, with scanf not, with get (s) when S is a string type when not, when with get (s), S is a char type, when using Getline (cin,s) when S is a string, or too vegetable
#include <iostream> #include <string.h> using namespace std;
string S;
int pos[105][105],dp[105][105];
void Show (int i,int j) {if (i>j) return; if (I==J)//Here is how to output {if (s[i]== ' | | |
s[i]== ') cout<< "()";
else cout<< "[]";
} else {if (pos[i][j]==-1)//Match {cout<<s[i];
Show (I+1,J-1);
cout<<s[j];
} else//Update {show (i,pos[i][j]);
Show (POS[I][J]+1,J);
}}} int main () {while (Getline (cin,s)) {memset (dp,0,sizeof (DP));
memset (Pos,0,sizeof (POS)); for (int i=1;i<s.size (), i++) for (int j=0,k=i;k<s.size (); j++,k++) {if (s[j]== ' (' &&s[k]== ') ' | |
s[j]== ' [' &&s[k]== '] ')//if matched to, {dp[j][k]=dp[j+1][k-1]+2; Pos[j][k]=-1; } for (int m=j;m<k;m++) {if (dp[j][m]+dp[m+1][k]>=dp[j][k])//Here is more
new {dp[j][k]=dp[j][m]+dp[m+1][k];
Pos[j][k]=m;
}}} show (0,s.size ()-1);
cout<<endl;
S.clear ();
} return 0;
}