题目:
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
思路:用DFS处理,如下图(画的有点丑)
处理的所有情况为:
- 没有括号余量。
- 左括号有余:添加左括号。
- 右括号有余且已用左括号数 > 右括号个数:添加右括号。
代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void dfs(char** ans, int left, int right, int n, int index, int* returnSize, char* str)
{
if (left == n && right == n)
{
ans[(*returnSize)] = (char*)calloc((2 * n + 1), sizeof(char));
strcpy(ans[(*returnSize)++], str);
return;
}
if (left < n)//左括号没用完
{
str[index] = '(';
dfs(ans, left + 1, right, n, index + 1, returnSize, str);
}
if (right < n && left > right)
{
str[index] = ')';
dfs(ans, left, right + 1, n, index + 1, returnSize, str);
}
return;
}
char ** generateParenthesis(int n, int* returnSize)
{
*returnSize = 0;
char* str = (char* )calloc(2 * n + 1, sizeof(char));
char** ans = (char** )malloc(sizeof(char* ) * 5000);
dfs(ans, 0, 0, n, 0, returnSize, str);
return ans;
}
注意点:
- str内存的申请用calloc,因为会将每一位初始化为’\0’,如果用malloc则没有初始化,在strcpy操作时会溢出(当然也可memset初始化什么的)。
- str[index] = ‘(’ 操作时不可用index++,内存会溢出,因为执行到加右括号时,添加的位置错误(是原来的后一位),当index > n时会溢出。