Skip to content

Commit 60af10a

Browse files
add problem 22 and test function
1 parent 6c117a1 commit 60af10a

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

C/1-50/22-Generate-Parentheses.c

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
3+
4+
* For example, given n = 3, a solution set is:
5+
* [
6+
"((()))",
7+
"(()())",
8+
"(())()",
9+
"()(())",
10+
"()()()"
11+
* ]
12+
* Created by supercoderx on 2017/8/10.
13+
*/
14+
#include <stdlib.h>
15+
#include <stdio.h>
16+
#include <string.h>
17+
18+
char** generateParenthesis(int n, int* returnSize) {
19+
*returnSize = 0;
20+
if(n<=0){
21+
return NULL;
22+
}
23+
char **result = malloc(sizeof(char*)), *str = NULL;
24+
int *curLeft = malloc(sizeof(int)),*allLeft=malloc(sizeof(int)),count;
25+
26+
for(int i = 0; i < 2*n;i++){
27+
if(i == 0 ){
28+
str = malloc(sizeof(char)*(2*n+1));
29+
str[0] = '(';
30+
str[2*n] = '\0';
31+
result[0] = str;
32+
curLeft[0] = 1;
33+
allLeft[0] = n-1;
34+
(*returnSize)++;
35+
}else{
36+
count = *returnSize;
37+
for(int j = 0; j<count;j++){
38+
if(curLeft[j]!=0 && allLeft[j]!=0){
39+
str = malloc(sizeof(char)*(2*n+1));
40+
str[2*n] = '\0';
41+
strcpy(str,result[j]);
42+
str[i] = '(';
43+
result[j][i] = ')';
44+
(*returnSize)++;
45+
curLeft = realloc(curLeft,sizeof(int)*(*returnSize));
46+
allLeft = realloc(allLeft,sizeof(int)*(*returnSize));
47+
result = realloc(result, sizeof(char*)*(*returnSize));
48+
curLeft[*returnSize-1] = curLeft[j]+1;
49+
allLeft[*returnSize-1] = allLeft[j]-1;
50+
result[*returnSize-1] = str;
51+
curLeft[j]--;
52+
}else if(curLeft[j] == 0 && allLeft[j]>0){
53+
result[j][i] = '(';
54+
allLeft[j]--;
55+
curLeft[j]++;
56+
}else if(allLeft[j]==0){
57+
result[j][i]=')';
58+
curLeft[j]--;
59+
}
60+
}
61+
}
62+
}
63+
return result;
64+
}
65+
66+
void testGenerateParenthesis(){
67+
int count = 0;
68+
char** result = generateParenthesis(3,&count);
69+
for(int i = 0; i < count;i++){
70+
printf("%s,",result[i]);
71+
}
72+
73+
}

0 commit comments

Comments
 (0)