import java.util.ArrayList;
import java.util.List;
/**
* @author xnl
* @Description:
* @date: 2022/8/1 21:56
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.generateParenthesis(3).toString());
}
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
dfs(list, new StringBuilder(), n, 0 , 0);
return list;
}
private void dfs(List<String> list, StringBuilder sb , int max, int open ,int close){
if (sb.length() == max * 2){
list.add(sb.toString());
return;
}
// 先添加左括号
if (open < max){
sb.append("(");
dfs(list, sb, max, open + 1, close);
sb.deleteCharAt(sb.length() - 1);
}
// 添加完之后添加右括号
if (close < open){
sb.append(")");
dfs(list, sb, max, open, close + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
08-14
1163
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)