GenerateParentheses

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:
"((()))", "(()())", "(())()", "()(())", "()()()"

Solution: Place n left '(' and n right ')'. Cannot place ')' if there are no enough matching '('.

 1 class Solution {
 2 public:
 3     void generateParenthesis(vector<string>& res, string& s, int l, int r) {
 4         if(l == 0 && r == 0) {
 5             res.push_back(s);
 6         }
 7         if(l > 0) {
 8             s.push_back('(');
 9             generateParenthesis(res, s, l-1, r);
10             s.pop_back();
11         }
12         if(r > l) {
13             s.push_back(')');
14             generateParenthesis(res, s, l, r-1);
15             s.pop_back();
16         }
17         
18     }
19     vector<string> generateParenthesis(int n) {
20         vector<string> res;
21         string s;
22         generateParenthesis(res,s,n,n);
23         return res;
24     }
25 };
原文地址:https://www.cnblogs.com/zhengjiankang/p/3645985.html