LeetCode,leetcodeoj
題目連結:Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
這道題的要求是給定n對括弧,產生所有正確的括弧組合。
這道題要產生正確形式的括弧匹配的數量,其實就是卡特蘭數,這裡就不詳說了。
至於要輸出所有括弧的正確組合形式,可以採用遞迴。用兩個變數l和r記錄剩餘左括弧和右括弧的數量,若且唯若左右括弧數量都為0時,正常結束。當然還有一點限制,就是剩餘的右括弧數量比左括弧多時才能添加右括弧。
時間複雜度:???(結果數量)
空間複雜度:???(結果數量)
1 class Solution 2 { 3 private: 4 void generateParenthesis(vector<string> &v, string s, int l, int r) // l和r記錄剩餘左右括弧的數量 5 { 6 if(l == 0 && r == 0) // 若且唯若左右括弧數量都為0時,正常結束 7 v.push_back(s); 8 9 if(l > 0)10 generateParenthesis(v, s + "(", l - 1, r);11 if(r > 0 && l < r) // 剩餘的右括弧數量比左括弧多時才能添加右括弧12 generateParenthesis(v, s + ")", l, r - 1);13 }14 public:15 vector<string> generateParenthesis(int n)16 {17 vector<string> v;18 generateParenthesis(v, "", n, n);19 return v;20 }21 };
轉載請說明出處:LeetCode --- 22. Generate Parentheses