用C++列印所有平衡括號的組合
在這個問題中,我們給定一個整數n。我們的任務是列印所有可能的n對平衡括號。
平衡括號是指每對開括號都有一個對應的閉括號,並且括號巢狀正確。
讓我們舉個例子來理解這個問題:
Input: n = 2 Output: {}{} {{}}
為了解決這個問題,我們需要跟蹤括號對。初始括號計數為0。然後,我們將遞迴呼叫一個函式,直到總括號計數小於n。計數括號,根據計數遞迴呼叫括號。如果開括號計數大於閉括號計數,則新增閉括號,然後處理剩餘的括號對計數;如果開括號計數小於n,則遞迴呼叫剩餘的括號對。
示例
下面的程式碼將展示我們解決方案的實現:
# include<iostream> using namespace std; # define MAX_COUNT 100 void printParenthesesPairs(int pos, int n, int open, int close){ static char str[MAX_COUNT]; if(close == n) { cout<<str<<endl; return; } else { if(open > close) { str[pos] = '}'; printParenthesesPairs(pos+1, n, open, close+1); } if(open < n) { str[pos] = '{'; printParenthesesPairs(pos+1, n, open+1, close); } } } int main() { int n = 3; cout<<"All parentheses pairs of length "<<n<<" are:\n"; if(n > 0) printParenthesesPairs(0, n, 0, 0); getchar(); return 0; }
輸出
All parentheses pairs of length 3 are − {}{}{} {}{{}} {{}}{} {{}{}} {{{}}}
廣告