LeetCode problem #22–Generate parentheses (JavaScript)
In this LeetCode challenge we’re asked to generate all possible combinations of open and closed parentheses, with a given number of available pairs. In other words, given the number 2, we should return ()()
and (())
. The only real condition is that these parentheses must be valid (opened and closed in order).
It seems apparent straight off the bat that this question requires some kind of exponential / expanding solution, as for every parentheses we add, we will then have two paths; whether to close that parentheses, or whether to open another one. For those two paths, each will then have another two, and so on, until we reach the point where we must start closing parentheses, and finally the point where we reach the maximum length.
Solution: Recursion
This solution does more or less exactly what is described above. We open an initial parentheses (as we must begin with an opening one), and then we start two paths; one that opens another one, and one that closes it. This is called recursively, and so although the code is fairly short, the implications are pretty big.