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.
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;
以上仅提供思路。