/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void generate(int left, int right, int n, char *str, int index, char **result, int *returnSize) {
// 当前长度已达2n,结束.
if (index == 2 * n) {
result[(*returnSize)] = (char*)calloc((2 * n + 1), sizeof(char));
strcpy(result[(*returnSize)++], str);
return;
}
//如果左括号数量小于n,放一个左括号
if (left < n) {
str[index] = '(';
generate(left + 1, right, n, str, index + 1, result, returnSize);
}
//如果右括号数量小于左括号的数量,放一个右括号
if (right < left) {
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 *) * 10000);
//返回
*returnSize = 0;
generate(0, 0, n, str, 0, result, returnSize);
return result;
}
LeetCode:22. 括号生成
最新推荐文章于 2024-07-25 17:54:26 发布