题目描述:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
解题思路:
基本想法是用递归,当左括号数 < n, 可以继续放左括号,当右括号数<左括号数时,可以继续放右括号。
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> result; 5 if (n > 0) { 6 generateParenthesis(n, "", 0, 0, result); 7 } 8 9 return result; 10 } 11 private: 12 void generateParenthesis(int n, string s, int l, int r, vector<string> &result) { 13 if (l == n) { 14 result.push_back(s.append(n - r, ')')); 15 return; 16 } 17 generateParenthesis(n, s + '(', l + 1, r, result); 18 19 if (r < l) { 20 generateParenthesis(n, s + ')', l, r + 1, result); 21 } 22 } 23 };