数字?
n
?代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且?有效的?括号组合。
class Solution {
List<String> ans = new ArrayList<>();
int size;
public List<String> generateParenthesis(int n) {
size = n;
dfs(0,0,new StringBuilder());
return ans;
}
private void dfs( int left, int right, StringBuilder sb){
if(right == size){
ans.add(sb.toString());
return;
}
if(left == right){
dfs(left + 1,right,new StringBuilder(sb).append("("));
} else if(left > right){
if(left < size){
dfs(left + 1,right,new StringBuilder(sb).append("("));
}
dfs(left,right + 1,new StringBuilder(sb).append(")"));
}
}
}