括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例:

输入:n = 3
输出:[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]


  1. vector<string> generateParenthesis(int n) {
  2. vector<string> res;
  3. func(res, "", 0, 0, n);
  4. return res;
  5. }
  6. void func(vector<string> &res, string str, int l ,int r, int n){
  7. if(l>n || r>n || r>l) return;
  8. if(l==n && r==n){
  9. res.push_back(str);
  10. return;
  11. }
  12. func(res, str+'(', l+1, r, n);
  13. func(res, str+')', l, r+1, n);
  14. return;
  15. }