输出n对括号的所有有效(左右括号成对匹配)排列

原题:Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.

EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))


下面这个程序是错的. 错在哪里了?

void PrintBracketsPairRecs(char *pBegin, char *pCur, int nCurLeft)
{
	if (nCurLeft == 1)
		{
		*pCur = '(';
		*(pCur+1) = ')';
		printf("%s\n", pBegin); // exit of recursive function
		}
	else
		{
		// 1st way: ()*********
		*pCur = '(';
		*(pCur+1) = ')';
		PrintBracketsPairRecs(pBegin, pCur+2, nCurLeft-1);

		// 2nd way: (*********)
		*pCur = '(';
		*(pCur + (nCurLeft)*2 - 1) = ')';
		PrintBracketsPairRecs(pBegin, pCur+1, nCurLeft-1);
		}
}

void PrintBracketsPair(int n)
{
	char *pBuffer = new char[2 * n + 1];
	memset(pBuffer, 0, sizeof(char) * 2 * n + 1);
	PrintBracketsPairRecs(pBuffer, pBuffer, n);
	delete [] pBuffer;
}

那么下面这个解法这个是对的吗?

void PrintBracketsPairRecs(char *pBegin, char *pCur, int nLeft, int nRight)
{
	if (nLeft == 0 && nRight >= 1)
		{
		for (int i=0; i<nRight; i++, pCur++)
			*pCur = ')';
		printf("%s\n", pBegin); // exit of recursive function
		}
	else if (nLeft > 0 && nLeft == nRight)
		{
		*pCur = '(';
		PrintBracketsPairRecs(pBegin, pCur+1, nLeft-1, nRight);
		}
	else if (nLeft > 0 && nLeft < nRight)
		{
		*pCur = '(';
		PrintBracketsPairRecs(pBegin, pCur+1, nLeft-1, nRight);

		*pCur = ')';
		PrintBracketsPairRecs(pBegin, pCur+1, nLeft, nRight-1);
		}
}

void PrintBracketsPair(int n)
{
	char *pBuffer = new char[2 * n + 1];
	memset(pBuffer, 0, sizeof(char) * 2 * n + 1);
	PrintBracketsPairRecs(pBuffer, pBuffer, n, n);
	delete [] pBuffer;
}

你可能感兴趣的:(输出n对括号的所有有效(左右括号成对匹配)排列)