First consider how to define the DP so that it satisfies having a sub-structure to solve,
define DP [i] [j] as the number I to the J bracket in the string maximum match
Then if we know the maximum match of the I to J interval, then the i+1 to the j+1 interval is not Can be very simple to get.
So if the first and the first J are a pair of matching parentheses then DP [i] [j] = DP [i+1] [j-1] + 2;
then we just need to enumerate all the parentheses in the middle of all I and j from small to large, then satisfy the match with the above formula DP, and then update DP [i] [j] to the maximum value each time.
The method of updating the maximum value is to enumerate the intermediate values of I and J, and then let dp[i] [j] = max (DP [i] [j], DP [i] [f] + DP [f+1] [j]);
for the first time with string, feel good, think this thing is a try to use, never to the process #include <iostream> #include <algorithm
> #include <string.h> using namespace std;
string S;
int dp[105][105]; int main () {while (cin>>s) {if (s== "end")//can also be written here s[0]== ' E ', s.length () can also be written s.size () Brea
K
Memset (Dp,0,sizeof (DP)); for (int i=1;i<=s.length (), i++) for (int j=0,k=i;k<s.length (); j++,k++) {i F (s[j]== ' (' &&s[k]== ') ' | |
s[j]== ' [' &&s[k]== '] ') dp[j][k]=dp[j+1][k-1]+2;
for (int m=j;m<k;m++) Dp[j][k]=max (Dp[j][k],dp[j][m]+dp[m+1][k]);
} cout<<dp[0][s.length () -1]<<endl;
} return 0; }