版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
考察:生成配对的括号,回溯法。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
if (left > right) // 放置出现')))((('
return ;
if (left == 0 && right == 0)
res.push_back(out);
else {
if (left > 0)
generateParenthesisDFS(left-1, right, out+'(', res);
if (right > 0)
generateParenthesisDFS(left, right-1, out+')', res);
}
}
};
完,