题目链接:https://ac.nowcoder.com/acm/problem/21303
dp[i][j][k]表示序列s1的前i个匹配序列s2的前j个,序列s1删除部分左括号与右括号数量差为k的情况是否可行
状态转移方程:
时间复杂度:O(n^3)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
static const int MAX_N = 105;
static const ll Mod = 1e9 + 7;
static const int N = 105;
static const ll INF = (ll)1 << 60;
char s1[MAX_N], s2[MAX_N];
bool dp[MAX_N][MAX_N][MAX_N];
int main() {
/*freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);*/
while (scanf("%s%s", s1, s2) != EOF) {
memset(dp, 0, sizeof(dp));
dp[0][0][0] = 1;
int la = strlen(s1), lb = strlen(s2);
for (int i = 0; i < la; ++i) {
for (int j = 0; j < lb; ++j) {
for (int k = 0; k < la; ++k) {
if (dp[i][j][k]) {
if (!k && s1[i] == s2[j]) dp[i + 1][j + 1][k] = 1;
if (s1[i] == '(') dp[i + 1][j][k + 1] = 1;
else if (k) dp[i + 1][j][k - 1] = 1;//这里需要注意防止数组越界
}
}
}
}
puts(dp[la][lb][0] ? "Possible" : "Impossible");
}
return 0;
}