-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path022-Generate Parentheses.c
51 lines (51 loc) · 1.33 KB
/
022-Generate Parentheses.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
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** generateParenthesis(int n, int* returnSize) {
int ls = 0, rs = 0, i;
char stack[2*n];
int top = 0;
char ** res = malloc(10000*sizeof(char*));
(* returnSize) = 0;
while (true) {
if (top == 2 * n) {
res[(* returnSize)] = malloc(top+1);
for (i = 0 ; i < top ; i++) {
res[(* returnSize)][i] = stack[i];
}
res[(* returnSize)][i] = '\0';
(* returnSize)++;
while (true) {
if (top == 0) {
break;
}
while (stack[top-1] == ')') {
rs--;
top--;
}
// stack[top-1] == '('
ls--;
top--;
if (ls <= rs) {
continue;
} else {
stack[top++] = ')';
rs++;
break;
}
}
}
if ((* returnSize) != 0 && top == 0) {
break;
}
if (ls < n) {
stack[top++] = '(';
ls++;
} else {
stack[top++] = ')';
rs++;
}
}
return res;
}