枚举起点和终点,当起点和终点匹配时,dp[start][end]=dp[start+1][end-1]+2
然后枚举中间点
#include<iostream>
#include<cstring>
using namespace std;
const int N=1010;
int dp[N][N];
string str;
int main()
{
while(cin>>str)
{
if(str[0]=='e')
break;
memset(dp,0,sizeof dp);
for(int len=1;len<=str.size();len++)
for(int start=0;start<str.size();start++)
{
int end=start+len-1;
if(end>=str.size())
continue;
if(str[start]=='('&&str[end]==')' || str[start]=='['&&str[end]==']')
dp[start][end]=dp[start+1][end-1]+2;
for(int k=start;k<=end;k++)
dp[start][end]=max(dp[start][end],dp[start][k]+dp[k+1][end]);
}
cout<<dp[0][str.size()-1]<<endl;
}
return 0;
}