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:

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

思路一:对于给定的n,有效的括号串长度为2n,我们可以遍历所有的串,如果是有效的,就保存下来。

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         if (n == 0)
 6             return res;
 7         generateParenthesis(0, n, "", res);
 8         return res;
 9     }
10 private:
11     void generateParenthesis(int current, const int n, string str, vector<string> &res) {
12         if (current == 2 * n) {
13             if (isValid(str))
14                 res.push_back(str);
15             return;
16         }
17         char c[2] = {'(', ')'};
18         for (int i = 0; i < 2; i++) { //当前位置有两种选择
19             generateParenthesis(current + 1, n, str + c[i], res);
20         }
21     }
22     bool isValid(string s) {
23         int len = s.length();
24         int distance = 0;
25         for (int i = 0; i < len; i++) {
26             if (s[i] == '(') {
27                 distance++;
28             } else {
29                 if (distance <= 0)
30                     return false;
31                 distance--;
32             }
33         }
34         return (distance == 0);
35     }
36 };

思路二:对于某个位置,可以放 '(' 的条件是当前'('放的个数小于n,可以放')'的条件是'('的个数大于')

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         if (n == 0)
 6             return res;
 7         generateParenthesis(0, 0, n, "", res);
 8         return res;
 9     }
10 private:
11     void generateParenthesis(int open, int close, const int n, string str, vector<string> &res) {
12         if (str.length() == 2 * n) {
13             res.push_back(str);
14             return;
15         }
16         if (open < n)
17             generateParenthesis(open + 1, close, n, str + '(', res);
18         if (open > close)
19             generateParenthesis(open, close + 1, n, str + ')', res);
20     }
21 };

 符合条件的个数是卡特兰数:

原文地址:https://www.cnblogs.com/qinduanyinghua/p/11537288.html