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:

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

递归与深搜。

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

 

相关文章:

  • 2021-08-19
  • 2022-02-15
  • 2022-01-15
猜你喜欢
  • 2021-05-06
  • 2022-01-12
  • 2021-06-30
  • 2021-09-30
  • 2022-03-10
  • 2021-10-19
  • 2021-11-04
相关资源
相似解决方案