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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
括号匹配。使用递归的方法。
设定left、right表示左右括号的剩余数,
如果left > right表示匹配失衡,直接返回。
如果left < right表示已经存在一个左括号,需要匹配下一次左括号或者右括号,进行递归。
如果left == right == 0,表示括号匹配完毕且合法。把当前括号序列放入结果数组中。
参考代码如下:
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; generateParenthesis(n, n, "", res); return res; } void generateParenthesis(int left, int right, string str, vector<string>& res) { if (left > right) { return; } if (left == 0 && right == 0) { res.push_back(str); } else { if (left > 0) { generateParenthesis(left-1, right, str+'(', res); } if (right > 0) { generateParenthesis(left, right-1, str+')', res); } } } };
另一种方法,提前剪枝,思路更清晰,left、right表示当前左右括号的数量
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; string out; dfs(n, 0, 0, out, res); return res; } void dfs(int n, int left, int right, string out, vector<string>& res) { if (left < n) { out.push_back('('); dfs(n, left+1, right, out, res); out.pop_back(); } if (left > right) { out.push_back(')'); dfs(n, left, right+1, out, res); out.pop_back(); } if (out.size() == n*2) res.push_back(out); } };