Description
Input
Output
Sample Input
([(]
Sample Output
()[()]
题意:给你一个含括号的字符串,问你最小添加多少括号能使这个字符串的括号完全匹配。可以记录dp[i][j]为区间[i,j]中所有括号全部匹配需要的最少括号数,c[i][j]表示区间[i,j]中断开的坐标,便于待会递归输出。当i==j时,c[i][j]=-1,dp[i][j]=1;当str[i]==str[j]时,dp[i][j]=dp[i+1][j-1];再进行状态转移方程dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]).同时更新c[i][j].
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<string> #include<algorithm> using namespace std; #define inf 99999999 int dp[106][106],c[106][106]; char str[106]; int ok(char a,char b){ if( (a=='('&&b==')') || (a=='[' && b==']'))return 1; return 0; } void shuchu(int l,int r) { int i,j; if(l>r)return; if(l==r){ if(str[l]=='(' || str[l]==')')printf("()"); else printf("[]"); return; } if(c[l][r]!=-1){ shuchu(l,c[l][r]); shuchu(c[l][r]+1,r); return; } else{ if(str[l]=='('){ printf("("); shuchu(l+1,r-1); printf(")"); } else{ printf("["); shuchu(l+1,r-1); printf("]"); } return; } } int main() { int n,m,i,j,len,len1,k,l,r; while(gets(str)>0) { memset(c,-1,sizeof(c)); len1=strlen(str); for(i=0;i<len1;i++){ dp[i][i]=1; } for(i=0;i<len1-1;i++){ if(ok(str[i],str[i+1]))dp[i][i+1]=0; else { dp[i][i+1]=2; c[i][i+1]=i; } } for(len=3;len<=len1;len++){ for(i=0;i+len-1<len1;i++){ j=i+len-1; dp[i][j]=inf; if(ok(str[i],str[j])){ dp[i][j]=dp[i+1][j-1]; c[i][j]=-1; } for(k=i;k<j;k++){ if(dp[i][j]>dp[i][k]+dp[k+1][j]){ dp[i][j]=dp[i][k]+dp[k+1][j]; c[i][j]=k; } } } } shuchu(0,len1-1); printf("\n"); } return 0; }