-
Notifications
You must be signed in to change notification settings - Fork 2
/
1183. Brackets Sequence.c
73 lines (60 loc) · 1.53 KB
/
1183. Brackets Sequence.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
int Pair[100] = {0};
void BackTr(int D[100][100], char S[100], int i, int j);
int main(void)
{
int i, j, k, N;
char S[100];
int D[100][100] = {0};
gets(S);
N = strlen(S);
for (i = 0; i < N; i++)
D[i][i] = 1;
for (j = 1; j < N; j++)
for (i = 0; i < N - j; i++)
{
int min = 100;
for (k = i; k < i + j; k++)
if (D[i][k] + D[k+1][i+j] < min)
min = D[i][k] + D[k+1][i+j];
if ((((S[i] == '[' && S[i+j] == ']') || (S[i] == '(' && S[i+j] == ')'))) && D[i+1][i+j-1] < min) min = D[i+1][i+j-1];
D[i][i+j] = min;
}
BackTr(D, S, 0, N - 1);
for (i = 0; i < N; i++)
if (Pair[i])
{
if (S[i] == '(' || S[i] == ')') printf("()");
if (S[i] == '[' || S[i] == ']') printf("[]");
} else printf("%c", S[i]);
return 0;
}
void BackTr(int D[100][100], char S[100], int i, int j)
{
if (i == j)
{
Pair[i] = 1;
return;
}
else
if (i > j)
return;
else
{
int k, ik;
int min = 100;
for (k = i; k < j; k++)
if (D[i][k] + D[k+1][j] < min)
{
min = D[i][k] + D[k+1][j];
ik = k;
}
if ((((S[i] == '[' && S[j] == ']') || (S[i] == '(' && S[j] == ')'))) && D[i+1][j-1] <= min)
BackTr(D, S, i+1, j-1);
else
{
BackTr(D, S, i, ik);
BackTr(D, S, ik + 1, j);
}
}
}