1111public class Number22括号生成 {
1212 public static void main (String [] args ) {
1313 // recursion(0, 3, "");
14- List <String > list = generateParenthesis (3 );
15- System .out .println (list );
14+ /* List<String> list = generateParenthesis(1);
15+ System.out.println(list);*/
16+ recursion (3 ,3 ,"" );
1617
1718 }
1819
1920 public static void recursion (int n , int max , String s ) {
20- if (n > = max ) {
21+ if (n < = max ) {
2122 System .out .println (s );
2223 return ;
2324 }
@@ -27,27 +28,32 @@ public static void recursion(int n, int max, String s) {
2728 System .out .println (s );
2829 }
2930
30- static List <String > res = new ArrayList <>();
3131
3232 public static List <String > generateParenthesis (int n ) {
33- dfs (n , n , "" );
33+ List <String > res = new ArrayList <>();
34+ dfs (n , n , "" ,res );
3435 return res ;
3536 }
3637
37- private static void dfs (int left , int right , String curStr ) {
38+ private static void dfs (int left , int right , String curStr , List < String > res ) {
3839 if (left == 0 && right == 0 ) { // 左右括号都不剩余了,递归终止
3940 res .add (curStr );
4041 return ;
4142 }
4243 if (left > 0 ) { // 如果左括号还剩余的话,可以拼接左括号
43- dfs (left - 1 , right , curStr + "(" );
44+ dfs (left - 1 , right , curStr + "(" , res );
4445 }
4546 if (right > left ) { // 如果右括号剩余多于左括号剩余的话,可以拼接右括号
46- dfs (left , right - 1 , curStr + ")" );
47+ dfs (left , right - 1 , curStr + ")" , res );
4748 }
4849 }
4950
51+
52+
5053 static class Number22括号生成2 {
54+ static List <String > res = new ArrayList <>();
55+
56+
5157 public static void main (String [] args ) {
5258 List <String > list = generateParenthesis (3 );
5359 System .out .println (list .toString ());
@@ -88,4 +94,7 @@ private static void dfs(int left, int right, String curStr) {
8894
8995 }
9096
97+
98+
99+
91100}
0 commit comments