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