【DP总结】【字符串】【POJ1141】

Description

Let us define a regular brackets sequence in the following way: 

1. Empty sequence is a regular sequence. 
2. If S is a regular sequence, then (S) and [S] are both regular sequences. 
3. If A and B are regular sequences, then AB is a regular sequence. 

For example, all of the following sequences of characters are regular brackets sequences: 

(), [], (()), ([]), ()[], ()[()] 

And all of the following character sequences are not: 

(, [, ), )(, ([)], ([(] 

Some sequence of characters '(', ')', '[', and ']' is given. You are to find the shortest possible regular brackets sequence, that contains the given character sequence as a subsequence. Here, a string a1 a2 ... an is called a subsequence of the string b1 b2 ... bm, if there exist such indices 1 = i1 < i2 < ... < in = m, that aj = bij for all 1 = j = n.

Input

The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.

Output

Write to the output file a single line that contains some regular brackets sequence that has the minimal possible length and contains the given sequence as a subsequence.

Sample Input

([(]

Sample Output

()[()]

Source

Northeastern Europe 2001


Solutions:

设m[i][j] 表示  str第i个字符到第j个字符 需要添加的最少括号数。
regs[i][j]表示str的第i个字符到第j个字符经过添加 m[i][j]个括号后所得的正则字符序列。

我们先讨论m[i][j]吧。

①  如果 str[ i ]==str[ j ]   则有 m[ i ][ j ]=min(m[ i ][ j ],m[ i+1 ][ j-1 ]);
②  如果 str[ i ] ! =str[ j ]  那么 m[ i ][ j ]=min(m[ i ][ k ]+m[ k+1 ][ j ]);

③  初值 : 如果 i==j  则有m[ i ][ j ]=1;

这里采用递归调用来实现,

讨论 regs[ i ][ j ]

①  如果 str[ i ]==str[ j ]   对于 reg 只用考虑 中间匹配的括号就好了。
一种情况是     reg[ i ][ j ]=' [  ' +  reg[ i+1 ][ j-1 ] + ' ] ' ;
一种情况是     reg[ i ][ j ]=' (  ' +  reg[ i+1 ][ j-1 ] + ' ) ' ;
当然这取决与 str[ i ] 咯。

②  如果 str[ i ] ! =str[ j ]   递归调用 regs[ i ] [ j ]=regs[ i ] [ k ] + regs [ k+1 ] [ j ]
③  初值 : 如果 i==j  则有m[ i ][ j ]=1;  只需要给 对应的str[ i ] 配对一个配对的括号就好了


综合可得。
m[i][j]=min(m[i][k]+m[k+1][j]) 且在最小情况下
reg[i][j]=reg[i][k]+reg[k+1][j]

最后输出的答案为。 reg[0][len-1]

时间复杂度 n*n*n; 
空间复杂度 n*n;

以上仅提供思路。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值