#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;
}


發佈了96 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章