标签:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
使用递归,从空字符串开始构造。
假设当前已经构造的是str, 剩余左右括号m, n:
如果m > 0, 说明还有左括号,可以直接加入左括号
如果n > 0 && n > m, 说明剩余右括号且个数大于左括号,可以放入右括号
1 vector<string> generateParenthesis(int n) 2 { 3 vector<string> results; 4 string s; 5 6 if (n > 0) 7 combination(results, s, n, n); 8 return results; 9 } 10 11 void combination(vector<string> &results, string s, int m, int n) 12 { 13 if (m == 0 && n == 0) 14 { 15 results.push_back(s); 16 return; 17 } 18 19 if (m > 0) 20 combination(results, s + "(", m - 1, n); 21 if ((n > 0) && (n > m)) 22 combination(results, s + ")", m, n - 1); 23 }
leetcode 22. Generate Parentheses
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4240244.html