本次题解思路参考来源如下:
作者:dingjinyang
链接: link.
来源:力扣(LeetCode)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_SIZE 1430
void huisu(int left,int right,int n,char *str,int index,char **result,int *returnSize) {
if(left == n && right == n) {//左右括号都已经用完
result[(*returnSize)] = (char *)calloc((2 * n + 1), sizeof(char));
strcpy(result[(*returnSize)++],str); //把找到的一个结果放入结果二维数组中
return;
}
if(left < n) { //当左括号还没用完时才执行
str[index] = '(';
huisu(left+1,right,n,str,index+1,result,returnSize); //继续探索左括号
}
if(right < n && right < left) { //左括号必须大于右括号,并且右括号没有用完
str[index] = ')';
huisu(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 *)*MAX_SIZE); //二维数组存放每一组结果
*returnSize = 0; //合题意的结果数量
huisu(0,0,n,str,0,result,returnSize);
return result;
}