您的位置:首页 > 其它

022 - Generate Parentheses

2015-11-11 18:22 316 查看
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"


给定一个数字,列出所有括号组合

void fun(int left, int right, char *line, int lp, char **result, int *returnSize)
{
if (left == 0) {
while (right--)
line[lp++] = ')';
memcpy(result[(*returnSize)++], line, lp);
return ;
}

if (left == right) {
line[lp++] = '(';
return fun(left - 1, right, line, lp, result, returnSize);
}

line[lp++] = '(';
fun(left - 1, right, line, lp, result, returnSize);
line[lp - 1] = ')';
fun(left, right - 1, line, lp, result, returnSize);
}

char** generateParenthesis(int n, int* returnSize)
{
int left = n, right = n;
char line[1024] = {0};
int lp = 0;
char **result = (char **)calloc(sizeof(char *), 8192);
int i;
for (i = 0; i < 8192; i++)
result[i] = (char *)calloc(sizeof(char), n + 1);
*returnSize = 0;
fun(left, right, line, lp, result, returnSize);
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: