使用记忆化搜索
/********************************************************************* 程序名: 版权: Joecai 作者: Joecai 日期: 2022-04-05 19:47 说明: *********************************************************************/ #include <bits/stdc++.h> using namespace std; #define x first #define y second # define rep(i,be,en) for(int i=be;i<=en;i++) # define pre(i,be,en) for(int i=be;i>=en;i--) typedef pair<int, int> PII; #define ll long long #define endl "\n" #define LOCAL #define pb push_back #define eb emplace_back #define sp(i) setprecision(i) const int N = 1e3 + 10, INF = 0x3f3f3f3f; int f[N][N]; int n; char s[N]; int dfs(int l, int r) { int res = 0; if (l >= r) { return f[l][r] = 0; } if (f[l][r] != -1) { return f[l][r]; } if (r == l + 1) { if (s[l] == '[' && s[r] == ']') f[l][r] = 2; else if (s[l] == '(' && s[r] == ')') f[l][r] = 2; else return f[l][r] = 0; } for (int i = l; i < r; i++) { res = max(res, dfs(l, i) + dfs(i + 1, r)); } if (s[l] == '[' && s[r] == ']' || s[l] == '(' && s[r] == ')') res = max(res, dfs(l + 1, r - 1) + 2); return f[l][r] = res; } void solve() { int n; cin >> n; memset(f, -1, sizeof(f)); cin >> s + 1; cout << dfs(1, n) << endl; } int main() { // std::ios::sync_with_stdio(false); // std::cin.tie(nullptr); //#ifdef LOCAL //freopen("data.in.txt","r",stdin); //freopen("data.out.txt","w",stdout); //#endif int __ = 1; //cin >> __; while (__--) { solve(); } return 0; }