22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Solution
C++
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, vector<string>& res, string cur) {
if(l == n && r == n) {
res.push_back(cur);
return;
}
if(l < n && r <= l) {
cur += "(";
dfs(n, l+1, r, res, cur);
cur.pop_back();
}
if(r < l) {
cur += ")";
dfs(n, l, r+1, res, cur);
cur.pop_back();
}
}
};
Explanation