##题目
22. 括号生成
##内容
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
##思路
实际就是模拟左右括号的摆放并且摆放过程中左括号一定大于等于右括号数量,这时候通过深搜就可以找到了
##代码
class Solution {
List<String> results;
public List<String> generateParenthesis(int n) {
results = new ArrayList<>();
dfs("", 0, 0, n);
return results;
}
public void dfs(String ans, int left, int right, int n) {
if (left == n && right == n) {
results.add(ans);
return;
}
if (left >= right && left <= n && right < n) {
dfs(ans + "(", left + 1, right, n);
}
if (left > right && left <= n && right < n)
dfs(ans + ")", left, right + 1, n);
}
}
##结果