原題: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: ()()(), ()(()), (())(), ((())) [cpp] 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; }