括号匹配: 递归+记录 诡异的是必须得while(gets(...))否则wa 见代码101行 代码很清楚: #include <iostream> #include <stdio.h> #include <algorithm> #include <cmath> #include <cstring> using namespace std; string str; int f[1001][1001]; int p[1001][1001]; int n; void MyScanf(int &num) { char a; while(a=getchar(),!isdigit(a)); num = a-'0'; while ((a = getchar())!=' ' && a!='/n') num = num*10 + a-'0'; } void Input() { } void Init() { int i,j; n = str.length() - 1; for (i = 1;i <= n;i++) for (j = 1;j <= n;j++) f[i][j] = -1; } int Dp(int i,int j) { if (f[i][j] != -1) return f[i][j]; if (i > j) f[i][j] = 0; else if (i == j) { f[i][j] = 1; if (str[i] == '(' || str[i] == ')') p[i][j] = -1; else p[i][j] = -2; } else { f[i][j] = 999999; if (str[i] == '(' && str[j] == ')' || str[i] == '[' && str[j] == ']') { if (f[i][j] > Dp(i + 1,j - 1)) { f[i][j] = Dp(i + 1,j - 1); p[i][j] = -3; } } int k; for (k = i;k < j;k++) { if (f[i][j] > Dp(i,k) + Dp(k + 1,j)) { f[i][j] = Dp(i,k) + Dp(k + 1,j); p[i][j] = k; } } } return f[i][j]; } void Print(int i,int j) { if (i > j) return; else if (i == j) { if (p[i][j] == -1) cout << "()"; if (p[i][j] == -2) cout << "[]"; return; } else if (p[i][j] == -3) { cout << str[i]; Print(i + 1,j - 1); cout << str[j]; } else { Print(i,p[i][j]); Print(p[i][j] + 1,j); } } void Compute() { Dp(1,n); Print(1,n); cout << endl; // int i,j; // for (i = 1;i <= n;i++) // for (j = i;j <= n;j++) // { // cout << i << " " << j << " " << f[i][j] << " " << p[i][j] << endl; // } } int main() { char temp[1001]; while (gets(temp)) { str = " "; str += temp; Input(); Init(); Compute(); } return 0; }