class Solution {
public:
vector<string> generateParenthesis(int n) {
std::string item;
dfs(item, 0, 0, n);
return result;
}
private:
void dfs(std::string& item, int open, int close, int n) {
if (item.size() == 2 * n) {
result.push_back(item);
return;
}
if (open < n) {
item.push_back('(');
dfs(item, open + 1, close, n);
item.pop_back();
}
if (close < open) {
item.push_back(')');
dfs(item, open, close + 1, n);
item.pop_back();
}
}
private:
std::vector<std::string> result;
};
——————————————————————————————————————————