// 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 统计过程中,左括号数大于等于右括号数。统计结束时,左右括号数相等
/*
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
/* 回溯法 */
void dfs(char **res, char *array, int n, int left, int right, int *returnSize)
{
if((left < right) || (left > n) || (right > n)) { // 此时不满足条件
return;
}
if((left == n) && (right == n)) {
res[*returnSize] = (char *)malloc(sizeof(char) * (2*n + 1));
if(res[*returnSize] == NULL){
return;
}
strcpy(res[*returnSize], array);
printf("res[%d] = %s, strlen(res) = %d\n", *returnSize, res[*returnSize], (unsigned int)strlen(res[*returnSize]));
(*returnSize)++;
return;
}
array[strlen(array)] = '(';
dfs(res, array, n, left + 1, right, returnSize);
array[strlen(array)-1] = '\0';
array[strlen(array)] = ')';
dfs(res, array, n, left, right + 1, returnSize);
array[strlen(array)-1] = '\0';
}
char ** generateParenthesis(int n, int* returnSize)
{
char *array = (char *)malloc(sizeof(char) * (2*n + 1));
if(array == NULL){
return NULL;
}
memset(array, '\0', sizeof(char) * (2*n + 1));
char **res = (char **)malloc(sizeof(char *) * 2000);
if(res == NULL){
return res;
}
dfs(res, array, n, 0, 0, returnSize);
free(array);
return res;
}
int main(void)
{
int n = 7;
int num = 0;
char **res = generateParenthesis(n, &num);
printf("num = %d\n", num);
system("pause");
}