Leetcode: Generate parentheses
Given a strictly positive integer
n, write a function that returns all possible combinations of well-formed parentheses.
Parentheses can be nested and added one after the other. It is important that we don’t create invalid combinations, such as
)(. The idea then becomes to start with a single set of parentheses
(). We can add another set of parentheses at three possible places:
1(2)3. When looking closely, we see that
3 are the same position.
We can then utilize Pythons string splitting capabilities which allow us to insert one or more characters at any place in the string. We do this by iterating over the string and inserting
() at every possible position. This creates all valid pairs like
To avoid the aforementioned duplicates we can add a memory to the function and store all the visited possible combinations. This allows us to speed the process up significantly. For example when we visit
()(), we don’t need to visit it again to form
n=3) because they would already been visited.
This solution beats 98% of all submitted solutions in terms of speed.