#22 Generate Parentheses

来源:互联网 发布:淘宝子账号登陆错误202 编辑:程序博客网 时间:2024/05/16 18:07

题目链接:https://leetcode.com/problems/generate-parentheses/


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:

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


/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */void generate(int n, char** ret, int *returnSize, char *tmpStr, int leftCount, int rightCount) {if (leftCount < n) { //左括号不到n个,可以放左括号tmpStr[leftCount + rightCount] = '(';generate(n, ret, returnSize, tmpStr, leftCount + 1, rightCount);}if (leftCount > rightCount && rightCount < n) {  //如果左括号多,可以放右括号tmpStr[leftCount + rightCount] = ')';generate(n, ret, returnSize, tmpStr, leftCount, rightCount + 1);}if (leftCount == n && rightCount == n) { //全部排序后保存输出tmpStr[leftCount + rightCount] = '\0';strcpy(ret[(*returnSize)++], tmpStr);}}char** generateParenthesis(int n, int* returnSize) {int i;int leftCount = 0, rightCount = 0;    char tmpStr[20] = {};char **ret = (char **)malloc(sizeof(char *) * 10000);for (i = 0; i < 10000; ++i)ret[i] = (char *)malloc(sizeof(char));//递归地输出每一个可能的字符。需要满右括号大于等于左括号generate(n, ret, returnSize, tmpStr, leftCount, rightCount);return ret;}


0 0