LeetCode 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.html

For example, given n = 3, a solution set is:測試

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

這道題是典型的回溯法的應用,使用遞歸寫代碼並不難,可是關鍵仍是須要理解流程,回溯法是指數的複雜度,所以測試用例中的數字應該不會太大spa

相似的題目有Valid ParenthesesLongest Valid Parenthesescode

 1 class Solution {
 2 public:
 3     //left 和 right 分別表示能夠用來放置的左括號和右括號
 4     vector<string> generateParenthesis(int n) {
 5         vector<string> res;
 6         generateParenthesis(n, n, "", res);
 7         return res;
 8     }
 9     void generateParenthesis(int left, int right, string out, vector<string> &res)
10     {
11         if (left > right)
12             return;
13         if (left == 0 && right == 0)
14             res.push_back(out);
15         else
16         {
17             if (left > 0)
18                 generateParenthesis(left - 1, right, out + "(", res);
19             if (right > 0)  //注意這裏的if 不能夠換成else與上一個if搭配,由於這裏並非非此即彼的關係
20                 generateParenthesis(left, right - 1, out + ")", res);
21         }
22             
23     }
24 };
相關文章
相關標籤/搜索