@@ -14,7 +14,8 @@ For example, given n = 3, a solution set is:
14
14
]
15
15
*/
16
16
17
- var generateParentheses = function ( n ) {
17
+ // ************************************************ Approach1 ************************************************
18
+ var generateParenthesesApproach1 = function ( n ) {
18
19
if ( n == 0 ) { return [ "" ] } ;
19
20
20
21
var str = "(" . repeat ( n ) ;
@@ -40,15 +41,58 @@ var genParAux = function(str, position, leftParentheses, sol) {
40
41
}
41
42
}
42
43
44
+ // ************************************************ Approach2 ************************************************
45
+ var generateParenthesesApproach2 = function ( n ) {
46
+ if ( n == 0 ) { return [ "" ] } ;
47
+
48
+ var sol = [ ] ;
49
+ genParAuxApproach2 ( "" , 0 , 0 , 0 , n * 2 , sol )
50
+ return sol ;
51
+ }
52
+
53
+ var genParAuxApproach2 = function ( str , leftPar , rightPar , index , totalCharCount , sol ) {
54
+ if ( index == totalCharCount ) {
55
+ if ( rightPar == leftPar ) {
56
+ sol . push ( str ) ;
57
+ }
58
+ return ;
59
+ }
60
+
61
+ var strLeft = insertAt ( str , index , "(" ) ;
62
+ genParAuxApproach2 ( strLeft , leftPar + 1 , rightPar , index + 1 , totalCharCount , sol ) ;
63
+
64
+ if ( rightPar == leftPar ) { return ; }
65
+
66
+ var strRight = insertAt ( str , index , ")" ) ;
67
+ genParAuxApproach2 ( strRight , leftPar , rightPar + 1 , index + 1 , totalCharCount , sol ) ;
68
+ }
69
+
70
+ var insertAt = function ( str , position , value ) {
71
+ return str . slice ( 0 , position ) + value + str . slice ( position ) ;
72
+ }
73
+
43
74
function main ( ) {
75
+ console . log ( "Approach 1" )
44
76
console . log ( "0:" ) ;
45
- console . log ( generateParentheses ( 0 ) ) ;
77
+ console . log ( generateParenthesesApproach1 ( 0 ) ) ;
46
78
console . log ( "1:" ) ;
47
- console . log ( generateParentheses ( 1 ) ) ;
79
+ console . log ( generateParenthesesApproach1 ( 1 ) ) ;
48
80
console . log ( "2:" ) ;
49
- console . log ( generateParentheses ( 2 ) ) ;
81
+ console . log ( generateParenthesesApproach1 ( 2 ) ) ;
50
82
console . log ( "3:" ) ;
51
- console . log ( generateParentheses ( 3 ) ) ;
52
- }
83
+ console . log ( generateParenthesesApproach1 ( 3 ) ) ;
84
+
85
+ console . log ( "-------------" ) ;
53
86
87
+ console . log ( "Approach 1" )
88
+ console . log ( "0:" ) ;
89
+ console . log ( generateParenthesesApproach2 ( 0 ) ) ;
90
+ console . log ( "1:" ) ;
91
+ console . log ( generateParenthesesApproach2 ( 1 ) ) ;
92
+ console . log ( "2:" ) ;
93
+ console . log ( generateParenthesesApproach2 ( 2 ) ) ;
94
+ console . log ( "3:" ) ;
95
+ console . log ( generateParenthesesApproach2 ( 3 ) ) ;
96
+ }
97
+ main ( ) ;
54
98
module . exports . main = main
0 commit comments