数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
来源:力扣(LeetCode)
void generate(int left, int right, int n, char *str, int index, char **result, int *returnSize) {
if (left == n && right == n) { //左右括号使用完
result[(returnSize)] = (char)malloc((2 * n + 1)*sizeof(char)); //为二维数组中的一维申请空间
strcpy(result[(*returnSize)++], str); // 拷贝str到result中
return;
}
if (left < n) { //左括号没用完
str[index] = ‘(’;
generate(left + 1, right, n, str, index + 1, result, returnSize);
}
if ( left > right &&right < n) { //右括号没用完且没结束时左括号数量一定大于右括号
str[index] = ‘)’;
generate(left, right + 1, n, str, index + 1, result, returnSize);
}
}
char **generateParenthesis(int n, int *returnSize) {
char str = (char)calloc((2 * n + 1), sizeof(char));
char **result = (char **)malloc(sizeof(char *) * 1500);
*returnSize = 0;
generate(0, 0, n, str, 0, result, returnSize);
return result;
}