1
+ package code ;
2
+ /*
3
+ * 22. Generate Parentheses
4
+ * 题意:正确括号组合的
5
+ * 难度:Medium
6
+ * 分类:String, Backtracking
7
+ * 思路:回溯法的典型题目,按选优条件向前搜索,达到目标后就退回一步或返回
8
+ * 注意:递归法别忘了两块的拼接,例如n=4时,可以由2,2拼起来作为答案
9
+ */
10
+ import java .util .ArrayList ;
11
+ import java .util .HashSet ;
12
+ import java .util .List ;
13
+ import java .util .Set ;
14
+
15
+ public class lc22 {
16
+ public static void main (String [] args ) {
17
+ System .out .println (generateParenthesis2 (4 ));
18
+ }
19
+
20
+ public static List <String > generateParenthesis (int n ) {
21
+ //递归法
22
+ Set <String > res = new HashSet <String >();
23
+ if (n ==1 ) {
24
+ res .add ("()" );
25
+ return new ArrayList (res );
26
+ }
27
+ List <String > temp = generateParenthesis (n -1 );
28
+ // 一个括号,和n-1个括号的组合
29
+ for (int i = 0 ; i < temp .size (); i ++) {
30
+ res .add ("(" +temp .get (i )+")" );
31
+ res .add ("()" +temp .get (i ));
32
+ res .add (temp .get (i )+"()" );
33
+ }
34
+ //2块拼一起
35
+ for (int j = 2 ; j <=n /2 ; j ++) {
36
+ List <String > temp1 = generateParenthesis (j );
37
+ List <String > temp2 = generateParenthesis (n -j );
38
+ for (int i = 0 ; i <temp1 .size () ; i ++) {
39
+ for (int k = 0 ; k < temp2 .size (); k ++) {
40
+ res .add (temp1 .get (i )+temp2 .get (k ));
41
+ res .add (temp2 .get (k )+temp1 .get (i ));
42
+ }
43
+ }
44
+ }
45
+ return new ArrayList (res );
46
+ }
47
+
48
+ public static List <String > generateParenthesis2 (int n ) {
49
+ //回溯法
50
+ ArrayList <String > res = new ArrayList <>();
51
+ backtracking (res ,"" , 0 , 0 , n );
52
+ return res ;
53
+ }
54
+
55
+ public static void backtracking (List <String > list ,String str ,int left , int right , int max ){
56
+ if (right ==max ){
57
+ list .add (str );
58
+ }
59
+ if (left <max )
60
+ backtracking (list ,str +"(" ,left +1 ,right ,max );
61
+ if (right <left )
62
+ backtracking (list ,str +")" ,left ,right +1 ,max );
63
+ }
64
+
65
+
66
+ }
0 commit comments