[LeetCode] 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
利用一个递归函数来产生,用一个参数来记录当前剩下可对应的左扩号数,只有leftNum > 0,才能加入右括号,同时增加一些剪支,例如leftNumTotal > n时说明左括号太多了,不可能产生合理解。
1 class Solution { 2 private: 3 vector<string> ret; 4 public: 5 void solve(int dep, int maxDep, int leftNum, int leftNumTotal, string s) 6 { 7 if (leftNumTotal * 2 > maxDep) 8 return; 9 10 if (dep == maxDep) 11 { 12 ret.push_back(s); 13 return; 14 } 15 16 for(int i = 0; i < 2; i++) 17 if (i == 0) 18 { 19 solve(dep + 1, maxDep, leftNum + 1, leftNumTotal + 1, s + '('); 20 } 21 else 22 { 23 if (leftNum > 0) 24 solve(dep + 1, maxDep, leftNum - 1, leftNumTotal, s + ')'); 25 } 26 } 27 28 vector<string> generateParenthesis(int n) { 29 // Start typing your C/C++ solution below 30 // DO NOT write int main() function 31 ret.clear(); 32 solve(0, 2 * n, 0, 0, ""); 33 return ret; 34 } 35 };