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:
void dfs(int n, int l, int r, vector<string> &ans, string &tmp) {
if (l >= r && l < n) {
tmp += '(';
dfs(n, l + 1, r, ans, tmp);
tmp.pop_back();
tmp += ')';
dfs(n, l, r + 1, ans, tmp);
tmp.pop_back();
}
if (l == n) {
if (r < n) {
tmp += ')';
dfs(n, l, r + 1, ans, tmp);
tmp.pop_back();
}
else {
ans.push_back(tmp);
}
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
string tmp = "(";
if (n == 0) {
return ans;
}
dfs(n, 1, 0, ans, tmp);
return ans;
}
};