题目
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来表示左右括号的剩余数量,右括号的剩余数量大于左括号时才能增加右括号。
class Solution {
public:
void DFS(vector<string> &res, int left, int right, string s) {
if(left == 0 && right == 0) res.push_back(s);
if(left > 0) DFS(res, left-1, right, s+"(");
if(right > 0 && left < right) DFS(res, left, right-1, s+")");
}
vector<string> generateParenthesis(int n) {
vector<string> res;
DFS(res,n,n,"");
return res;
}
};