1
+ /**
2
+ * Problem: Leet Code 22
3
+ * Solution: Uses a brute force approach of creating all the possible permutations.
4
+ * Basic fundamental of permutation is making all the possible choices at each step.
5
+ * As we explore all the possible choices at each step, the solution space will explode
6
+ * for us leading to an exponential solution. We use recursion to explore and a base condition
7
+ * to stop where all the positions for the choices have been explored.
8
+ *
9
+ * Complexity: Time O(2^n * n) since the entire permutation space has to be explored.
10
+ * Additionally, each string also needs to be validated for correctness in O(n) time.
11
+ * Space: O(2^n) assuming all the possible strings are valid.
12
+ *
13
+ * @param n
14
+ */
15
+ function generateParenthesis ( n : number ) : string [ ] {
16
+ return generateParanthesisHelper ( n * 2 )
17
+ } ;
18
+
19
+ function generateParanthesisHelper ( n : number , curr : number = 0 , result : string [ ] = [ ] ) : string [ ] {
20
+
21
+ const output : string [ ] = [ ] ;
22
+
23
+ if ( curr >= n ) {
24
+ // Done for all the positions, validate the created string.
25
+ if ( isValidParanthesis ( result ) )
26
+ output . push ( result . join ( "" ) )
27
+
28
+ return output ;
29
+ }
30
+
31
+ // At the position curr, choose one of the braces and recursively move.
32
+ result [ curr ] = "("
33
+ output . push ( ...generateParanthesisHelper ( n , curr + 1 , result ) ) ;
34
+
35
+ // At the position curr, choose one of the braces and recursively move.
36
+ result [ curr ] = ")"
37
+ output . push ( ...generateParanthesisHelper ( n , curr + 1 , result ) ) ;
38
+
39
+ // Return the final results.
40
+ return output ;
41
+
42
+ }
43
+
44
+ function isValidParanthesis ( result : string [ ] ) {
45
+ let braces = 0 ;
46
+ for ( let idx = 0 ; idx < result . length ; idx ++ ) {
47
+ if ( result [ idx ] === "(" ) braces ++
48
+ else if ( result [ idx ] === ")" ) braces -- ;
49
+
50
+ if ( braces < 0 ) return false
51
+ }
52
+
53
+ return braces === 0 ;
54
+ }
55
+
56
+ console . log ( generateParenthesis ( 3 ) )
0 commit comments