【
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
对C语言而言,这道题真的不简单,有几个点需要注意。
返回值是char型的二维数组,所以必须知道二维数组的申请方式,malloc一次后再for循环malloc一次。其中还要考虑二维数组传参问题,不过malloc方式申请的二维数组的,直接传指针就好了。
然后需要使用深度搜索DFS算法。对于嵌入式类的开发人员,最忌讳的就是使用递归,因为栈空间非常有限,一不小心就容易爆栈。而DFS的算法就是使用递归的思想,适应起来要克服一定的困难。
接着在DFS函数内每匹配一个有效括号组合,就需要及时拷贝进数组,memcpy。
最后才是此题的DFS思想,已使用的左括号可以比右括号多,但使用的右括号一定不能比左括号多。算法便是当还有剩余左括号,可以继续dfs下去。仅仅当剩余左括号比右括号少,才可以添加右括号dfs下去。
此题值得多看几遍。
int retcount = 0;
void dfs(char **retarr, int flag, int left, int right, char *temp, int tnum) {
if(flag == 0) {
temp[tnum] = '(';
} else {
temp[tnum] = ')';
}
tnum = tnum + 1;
if((left == 0) && (right == 0)) {
memcpy(retarr[retcount], temp, sizeof(char) * tnum);
retcount++;
return;
}
if (left > 0) {
dfs(retarr, 0, left - 1, right, temp, tnum);
}
if (left < right) {
dfs(retarr, 1, left, right - 1, temp, tnum);
}
}
char ** generateParenthesis(int n, int* returnSize){
char **retarr;
int i;
char *temp;
int tempnum = 0;
int len = 2 * n + 1;
temp = (char *)malloc(sizeof(char) * len);
memset(temp, 0, sizeof(char) * len);
retcount = 0;
retarr = (char **)malloc(sizeof(char *) * 8096);
for(i = 0; i < 8096; i++) {
retarr[i] = (int *)malloc(sizeof(char) * len);
memset(retarr[i], 0, sizeof(char) * len);
}
dfs(retarr, 0, n-1, n, temp, tempnum);
*returnSize = retcount;
free(temp);
return retarr;
}