LeetCode 22. 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:

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

 

这道题是典型的回溯法的应用,使用递归写代码并不难,但是关键还是需要理解流程,回溯法是指数的复杂度,因此测试用例中的数字应该不会太大

类似的题目有Valid ParenthesesLongest Valid Parentheses

 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 };

 

posted @ 2018-10-30 22:30  皇家大鹏鹏  阅读(126)  评论(0编辑  收藏  举报