原题:括号生成
数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
思路:
- 左括号随时可以加, 只要不超过n
- 右括号 左括号个数大于右括号
左右括号都用完,将结果加入返回集合
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
parentthesis(0, 0, "", n, res);
return res;
}
public void parentthesis(int left, int right, String str, int n, List<String> res) {
if (left == n && right == n) {
res.add(str);
return;
}
//左括号还未用完,用左括号
if (left < n) {
parentthesis(left + 1, right, str + "(", n, res);
}
//左括号比右括号多,使用右括号
if (left > right) {
parentthesis(left, right + 1, str + ")", n, res);
}
}