LeetCode,leetcodeoj

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.