首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2013-01-08 
输出n对括号的所有有效(左右括号成对匹配)排列原题:Implement an algorithm to print all valid (e.g., pr

输出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;}




热点排行