题目描述
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;
dfs(n, 0, 0, "", res);
return res;
}
void dfs(int n, int l, int r, string cur, vector<string>& res) {
if (r > l) return;
if (r == n) {
res.push_back(cur);
return;
}
if (l < n) dfs(n, l+1, r, cur+'(', res);
if (r < n) dfs(n, l, r+1, cur+')', res);
return;
}
};