4 [] ([])[] ((] ([)]
0 0 3 2
分析:我们用d[i][j]来表示从i到j之间要插入的个数。
则有以下情况:当s[i]与s[j]配对的时候此时有dp[i][j] = min(dp[i][j], dp[i+1][j-1]),之后呢就对i和j进行区间分割比较。
代码1(普通):
#include <stdio.h> #include <string.h> #include <algorithm> #define INF 0x3f3f3f3f #define M 105 using namespace std; char s[M]; int dp[M][M]; int main(){ int t; scanf("%d", &t); while(t --){ scanf("%s", s); memset(dp, 0, sizeof(dp)); int i, len = strlen(s), j; for(i = 0; i < len; i ++) dp[i][i] = 1; for(int l = 1; l < len; l ++){ for(i= 0;i < len-l; i ++){ j = l+i; dp[i][j] = INF; if((s[i] == '['&&s[j] == ']')||(s[i] == '('&&s[j] == ')')) dp[i][j] = min(dp[i][j], dp[i+1][j-1]); for(int m = i; m < j; m ++) dp[i][j] = min(dp[i][j], dp[i][m]+dp[m+1][j]); } } printf("%d\n", dp[0][len-1]); } return 0; }
#include <stdio.h> #include <string.h> #include <algorithm> #define INF 0x3f3f3f3f #define M 105 using namespace std; char s[M]; int d[M][M]; int f(int x, int y){ if(x > y) return 0; if(d[x][y] != -1) return d[x][y]; if(x == y){ d[x][x] = 1; return d[x][x]; } int i, va = INF; if((s[x] == '('&&s[y] == ')')||(s[x] == '['&&s[y] == ']')) va = min(va, f(x+1, y-1)); for(i = x; i < y; i ++){ va = min(va, f(x, i)+f(i+1, y)); } return d[x][y] = va; } int main(){ int t; scanf("%d", &t); while(t --){ scanf("%s", s); memset(d, -1, sizeof(d)); printf("%d\n", f(0, strlen(s)-1)); } return 0; }
原文地址:http://blog.csdn.net/shengweisong/article/details/40375139