题目链接: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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/ice_camel/article/details/46880195