首页 > 其他 > 详细

#22 Generate Parentheses

时间:2015-07-14 17:59:44      阅读:236      评论:0      收藏:0      [点我收藏+]

题目链接: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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

#22 Generate Parentheses

原文:http://blog.csdn.net/ice_camel/article/details/46880195

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!