import java.util.ArrayList;
/**
* @author xienl
* @description 括号生成
* @date 2022/7/5
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.generateParenthesis(3).toString());
}
public ArrayList<String> generateParenthesis (int n) {
// write code here
if (n == 0){
return new ArrayList<>();
}
ArrayList<String> res = new ArrayList<>();
bfs(res, "", 3,0 , 0);
return res;
}
private void bfs(ArrayList<String> res, String sb, int n, int left, int right){
if (left == n && right == n){
res.add(sb);
return;
}
if (left < n){
bfs(res, sb + "(", n,left + 1, right);
}
if (right < n && left > right){
bfs(res, sb + ")", n , left, right + 1);
}
}
}
牛客网:NC26 括号生成
最新推荐文章于 2026-06-22 22:46:40 发布
本文介绍了一个使用广度优先搜索(BFS)实现的括号生成算法。该算法能够生成所有合法的由n对括号组成的组合。通过递归地添加左括号和右括号,并确保任何时候右括号的数量不超过左括号的数量来保证合法性。

205

被折叠的 条评论
为什么被折叠?



