LeetCode --- 22. Generate Parentheses
阿新 • • 發佈:2019-02-13
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 };