I said that I would write a blog in English.
Now tyvj looks like vijos more.
tyvj1193
http://new.tyvj.cn/p/1193
It is an example given by Rujia Liu,in his book 《算法艺术与计算机竞赛》. Becase the brackets subsequence is defined in a recursive way, we can write state transition equations in a recursive way like this:
Let f[i][j] means the brackets we have to use to complete the subsequence from i to r in the oringinal sequence at least.
f[i][j]=f[i+1][j-1]; (if a[i] matches a[j])
f[i][j]=min(f[i][k]+f[k+1][j]); (for each k belongs to interval [l,r])
f[i][i]=0;(it is obvious)
In practise, we can use memorized search.
#include<bits/stdc++.h>
using namespace std;
const int maxn=300;
int n;
int a[maxn];
char s[maxn];
int f[maxn][maxn];
int search(int l,int r){
if (l>r){ f[l][r]=0; return f[l][r];}
if (l==r){ f[l][r]=1; return f[l][r];}
if (f[l][r]!=-1) return f[l][r];
f[l][r]=0x3f3f3f3f;
if ((s[l]=='('&&s[r]==')')||(s[l]=='['&&s[r]==']')) f[l][r]=search(l+1,r-1);
for(int i=l;i<r;i++)
f[l][r]=min(f[l][r],search(l,i)+search(i+1,r));
return f[l][r];
}
int main(){
scanf("%s",s);
n=strlen(s);
memset(f,255,sizeof f);
printf("%d",search(0,strlen(s)-1));
}