22. 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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解题思路:
这个是用迭代方法,当左括号和又括号的个数相同且等于输入n时将此时的字符串存入vector中。
这题是用回溯方法估计会更好些。
代码:
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> ret; 5 generate(n, 0, 0, "", ret); 6 return ret; 7 } 8 void generate(int n, int numl, int numr, string str, vector<string>& ret) { 9 if (numl < numr || numl > n || numr > n) 10 return; 11 if (numl == n && numr == n) 12 ret.push_back(str); 13 if (numl < n) { 14 generate(n, numl+1, numr, str+"(", ret); 15 generate(n, numl, numr+1, str+")", ret); 16 } else { 17 generate(n, numl, numr+1, str+")", ret); 18 } 19 } 20 };