1.dp[i][j]表示从i到j匹配的括号的最大数量。
2.转移方程dp[i][j] = max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);
表示当第k个括号和第i个括号匹配时,即ss[i] == ss[k]
括号数量为第i+1~k-1的括号数量和第k+1~j的括号数量+2
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
string ss;
int dp[105][105];
int main()
{
char ss[105];
while(~scanf("%s",ss+1))
{
if(strcmp(ss+1,"end") == 0)
break;
int len = strlen(ss+1);
memset(dp,0,sizeof(dp));
for(int i = len-1 ; i>=1 ; i--)
{
for(int j = i+1 ; j<=len ;j++)
{
dp[i][j] = dp[i+1][j];
if(ss[i] == '('||ss[i]=='[')
{
for(int k = i+1 ; k <= j ; k++)
{
if(ss[i]=='('&&ss[k]==')'||ss[i]=='['&&ss[k]==']')
dp[i][j] = max(dp[i][j],dp[i+1][k-1]+dp[k+1][j]+2);
}
}
}
}
cout<<dp[1][len]<<endl;
}
return 0;
}