22. 括号生成
数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
class Solution {
// (
//
// (( ()
//
// ((( (() ()( ())×
//
// ((() (()( (()) ()(( ()()
// ((()) (()() (())( ()(() ()()(
// ((())) (()()) (())() ()(()) ()()()
// 回溯的解法
public List<String> generateParenthesis(int n) {
// result:存放的结果集.temp:每层回溯存放暂时的结果.n:共有几层.index:第几层了.left:左括号有几个,right:右括号有几个。
List<String> result = new ArrayList<>();
StringBuffer temp = new StringBuffer();
int index = 0, left = 0, right = 0;
huisu(result, temp, 0, n * 2, left, right);
return result;
}
public void huisu(List<String> result, StringBuffer temp, int index, int n, int left, int right){
if(index == n){
result.add(temp.toString());
} else {
// 如果右括号的数量等于左括号---------->左括号
// 否则有两种情况
// 1.左括号满了,右括号少于左括号.----------->右括号
// 2.左括号没满,右括号少于左括号.----------->左右括号
if(left == right){
temp.append("(");
huisu(result, temp, index + 1, n, left + 1, right);
temp.deleteCharAt(index);
} else {
if(left == n / 2){
temp.append(")");
huisu(result, temp, index + 1, n, left, right + 1);
temp.deleteCharAt(index);
} else {
for (int i = 1; i <= 2; ++i) {
if (i == 1) {
temp.append("(");
huisu(result, temp, index + 1, n, left + 1, right);
temp.deleteCharAt(index);
} else {
temp.append(")");
huisu(result, temp, index + 1, n, left, right + 1);
temp.deleteCharAt(index);
}
}
}
}
}
}
}