File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/generate-parentheses
2
+ // T: O(Catalan-number(n)) or O(4^n/sqrt(n))
3
+ // S: O(Catalan-number(n)) or O(4^n/sqrt(n))
4
+
5
+ import java .util .ArrayList ;
6
+ import java .util .HashMap ;
7
+ import java .util .List ;
8
+ import java .util .Map ;
9
+
10
+ public class GenerateParentheses {
11
+ private static final Map <Integer , List <String >> VALID_PARENTHESES = new HashMap <>();
12
+
13
+ static {
14
+ VALID_PARENTHESES .put (0 , List .of ("" ));
15
+ VALID_PARENTHESES .put (1 , List .of ("()" ));
16
+ for (int i = 2 ; i <= 8 ; i ++) {
17
+ addValidParentheses (i );
18
+ }
19
+ }
20
+
21
+ private static void addValidParentheses (int i ) {
22
+ final List <String > result = new ArrayList <>();
23
+ addValidParentheses (i , result );
24
+ VALID_PARENTHESES .put (i , result );
25
+ }
26
+
27
+ private static void addValidParentheses (int i , List <String > result ) {
28
+ for (int k = 0 ; k < i ; k ++) {
29
+ for (String s1 : VALID_PARENTHESES .get (i - k - 1 )) {
30
+ for (String s2 : VALID_PARENTHESES .get (k )) {
31
+ result .add ("(" + s1 + ")" + s2 );
32
+ }
33
+ }
34
+ }
35
+ }
36
+
37
+ public List <String > generateParenthesis (int n ) {
38
+ return VALID_PARENTHESES .get (n );
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments