题目描述: 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
获得更多?
算法思路,案例演示,代码文档,算法解析的私得
算法思想: 使用了递归回溯的思想来生成有效的括号组合
项目源码
/**
* 2 * @Author: LJJ
* 3 * @Date: 2023/7/19 9:30
* 4
*/
import java.util.ArrayList;
import java.util.List;
public class GenerateParentheses {
public static List<String> generateParentheses(int n) {
List<String> result = new ArrayList<>();
backtrack(result, "", 0, 0, n);
return result;
}
private static void backtrack(List<String> result, String current, int open, int close, int n) {
// 终止条件:当当前括号组合的长度达到 2n 时,添加到结果集中
if (current.length() == 2 * n) {
result.add(current);
return;
}
// 如果左括号数量小于 n,则可以继续添加左括号
if (open < n) {
backtrack(result, current + "(", open + 1, close, n);
}
// 如果右括号数量小于左括号数量,则可以继续添加右括号
if (close < open) {
backtrack(result, current + ")", open, close + 1, n);
}
}
public static void main(String[] args) {
int n = 3;
List<String> parentheses = generateParentheses(n);
System.out.println("Valid Parentheses Combinations for n=" + n + ":");
for (String combination : parentheses) {
System.out.println(combination);
}
}
}