[LeetCode] 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:

"((()))", "(()())", "(())()", "()(())", "()()()"

 

利用一個遞歸函數來產生,用一個參數來記錄當前剩下可對應的左擴號數,只有leftNum > 0,才能加入右括號,同時增加一些剪支,例如leftNumTotal > n時說明左括號太多了,不可能產生合理解。

 1 class Solution {
 2 private:
 3     vector<string> ret;
 4 public:
 5     void solve(int dep, int maxDep, int leftNum, int leftNumTotal, string s)
 6     {
 7         if (leftNumTotal * 2 > maxDep)
 8             return;
 9             
10         if (dep == maxDep)
11         {
12             ret.push_back(s);
13             return;
14         }
15         
16         for(int i = 0; i < 2; i++)
17             if (i == 0)
18             {
19                 solve(dep + 1, maxDep, leftNum + 1, leftNumTotal + 1, s + '(');
20             }
21             else
22             {
23                 if (leftNum > 0)
24                     solve(dep + 1, maxDep, leftNum - 1, leftNumTotal, s + ')');
25             }
26     }
27     
28     vector<string> generateParenthesis(int n) {
29         // Start typing your C/C++ solution below
30         // DO NOT write int main() function
31         ret.clear();
32         solve(0, 2 * n, 0, 0, "");
33         return ret;
34     }
35 };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM