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 括号生成
最新推荐文章于 2024-07-29 14:22:26 发布