题目描述:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
题目解答:
方法1:回溯算法
for
循环+递归。记录当前用的左括号数目bef
及未成对的左括号数目single
,根据这两个数字可以计算出当前用了多少个字符。另外如果当前没有未成对的左括号,则需要先放置左括号。有未成对的左括号时,这个位置可以放置左括号,也可以放置右括号,但需要更新记录的数目。
注意优先级问题,++
的优先级高于*
。运行时间0ms,代码如下。
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void backTrack(char*** result, int* size, char* before, int bef, int n, int single) {
int i = 0, j = 0;
j = (bef - single) * 2 + single;
if(bef == n) {
for(j; j < 2 * n; j++)
before[j] = ')';
(*size)++;
*result = (char**)realloc(*result, *size * sizeof(char*));
result[0][