当前位置:编程学习 > C/C++ >>

输出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: ()()(), ()(()), (())(), ((()))
[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;  
}  
 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,