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.
输入
The input file contains at most 100 brackets (characters '(', ')', '[' and ']') that are situated on a single line without any other characters among them.
输出
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.
样例输入
([(]
样例输出
()[()]
一道难度较高的区间dp题,而且还要注意空串的特判处理。
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
constexpr int MAXN = 1e6;
constexpr int MOD = 1e9 + 7;
int main() {
string s;
getline(cin, s);
if (s.size() == 0) {
printf("\n");
return 0;
}
auto match = [](char a, char b) {
return (a == '(' && b == ')') || (a == '[' && b == ']');
};
vector<vector<int>> dp(101, vector<int>(101, s.size()));
//dp[i][j] = dp[i + 1][j - 1] (s[i] match s[j])
//初始化两种情况的初始情况分别为长度为0和长度为1
for (int i = 0; i < s.size(); i++) {
dp[i + 1][i] = 0;
dp[i][i] = 1;
}
// 从后枚举起点,得到起点到最后一个字符的所有状态值再向前延展
for (int i = s.size() - 2; i >= 0; i--) {
for (int j = i + 1; j < s.size(); j++) {
if (match(s[i], s[j])) {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1]);
}
for (int k = i; k < j; k++) {
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]);
}
}
}
function<void(int, int)> output = [&](int i, int j) {
if (i > j) return;
else if (i == j) {
if (s[i] == '(' || s[i] == ')') {
printf("()");
}
else printf("[]");
}
else if (match(s[i], s[j]) && dp[i][j] == dp[i + 1][j - 1]) {
//首先需要match确保是一对,其次要保证把这一对去掉修改次数不变
//原因在于不是如此可能把实际上错位匹配的一对括号配对了
printf("%c", s[i]);
output(i + 1, j - 1);
printf("%c", s[j]);
}
else {
//枚举中间点寻找最优的分割点
for (int k = i; k < j; k++) {
//dp数组中只有最好的分割点满足这个等式
if (dp[i][j] == dp[i][k] + dp[k + 1][j]) {
//递归的分别输出
output(i, k);
output(k + 1, j);
return;
}
}
}
};
output(0, s.size() - 1);
return 0;
}