#22 Generate Parentheses

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值