题意:给一个括号串,求最大匹配。
题解:记忆化搜索,dp[i][j]为[i,j]的最大匹配,dp[i][j]=max(dp[i+1][j-1]+corr(s[i],s[j]),dp[i][k]+dp[k+1][j]);
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int dp[105][105]; 6 char s[105]; 7 int corr(char a,char b) 8 { 9 if((a=='('&&b==')')||(a=='['&&b==']')) 10 return 1; 11 else 12 return 0; 13 } 14 int dfs(int l,int r) 15 { 16 if(l>=r) 17 return 0; 18 else if(dp[l][r]>=0) 19 return dp[l][r]; 20 else 21 { 22 int ans=dfs(l+1,r-1)+corr(s[l],s[r]); 23 for(int i=l;i<r;i++) 24 ans=max(ans,dfs(l,i)+dfs(i+1,r)); 25 return dp[l][r]=ans; 26 } 27 } 28 int main() 29 { 30 while(gets(s)&&s[0]!='e') 31 { 32 memset(dp,-1,sizeof(dp)); 33 printf("%d\n",dfs(0,strlen(s)-1)*2); 34 } 35 return 0; 36 }