回溯-22括号生成
package com.dkd;import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.*;public class a {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入括号对数 n: ");int n = scanner.nextInt();Solution solution = new Solution();List<String> result = solution.generateParenthesis(n);System.out.println("所有合法的括号组合:");for (String s : result) {System.out.println(s);}scanner.close();}
}class Solution {public List<String> generateParenthesis(int n) {List<String> result = new ArrayList<>();backtrack(n, 0, 0, new StringBuilder(), result);return result;}private void backtrack(int n, int left, int right, StringBuilder path, List<String> result) {// 终止条件:路径长度达到 2n,说明已经用了 n 个 '(' 和 n 个 ')'if (path.length() == n * 2) {result.add(path.toString());return;}// 尝试添加左括号 '(',前提是还没用完 n 个if (left < n) {path.append('(');backtrack(n, left + 1, right, path, result);path.deleteCharAt(path.length() - 1); // 回溯}// 尝试添加右括号 ')',前提是右括号数量小于左括号(保证合法性)if (right < left) {path.append(')');backtrack(n, left, right + 1, path, result);path.deleteCharAt(path.length() - 1); // 回溯}}
}
n = 2 的算法执行生成顺序

n= 3时候。执行生成顺序
递归同层时在下图同高度;往下递归时会分情况;往上回溯时,有的已经执行过就不执行了;
基本上同一层两种情况

