数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路:采用dfs回溯法(参考leetcode题解)
判断回溯很简单,拿到一个问题,你感觉如果不穷举一下就没法知道答案,那就可以开始回溯了。
一般回溯的问题有三种:
Find a path to success 有没有解 Find all paths to success 求所有解 求所有解的个数
求所有解的具体信息 Find the best path to success 求最优解 回溯法是一个剪枝了的二叉树。我们要得到的结果是可以
good leaf,如果不满足 good leaf 就继续向下搜索,搜索的时候需要满足一定的条件。
本题中dfs递归树如图所示,二叉树中向左代表添加左括号,向右代表添加右括号。
字符串中左括号数量要大于等于右括号数量,递归边界为左括号数量=右括号数量=n,即图中红线标出的5种情况,添加进答案数组中即可。
AC代码:(C++)
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
int lc = 0, rc = 0; //左括号和右括号的个数
dfs(res, "", n, lc, rc);
return res;
}
void dfs(vector<string> &res, string path, int n, int lc, int rc) {
if (rc > lc || rc > n || lc > n) return;
if (lc == rc && lc == n) {
res.push_back(path);
return;
}
dfs(res, path + '(', n, lc + 1, rc);
dfs(res, path + ')', n, lc, rc + 1);
}
};