https://leetcode-cn.com/problems/generate-parentheses/
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
回溯法
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
int left = 0, right = 0;
dfs(res, "", left, right, n);
return res;
}
void dfs(vector<string>& res, string path, int left, int right, int n) {
if (left > n || left < right) return ;
if (left == n && left == right) {
res.push_back(path);
return;
}
dfs(res, path + '(', left + 1, right, n);
dfs(res, path + ')', left, right + 1, n);
}
};