Parens
8.9 Parens: Implement an algorithm to print all valid (Le., properly opened and closed) combinations of n pairs of parentheses.
All valid parenthesis could be built with the base case
()
or""
.For every case forward, we can build every other valid combination by one of two cases: 1) we always insert to the front of the string. 2) for every opening brace
(
presents a new opportunity to add and additional()
, since we assume that all previous states are valid and therefore so(
guarantees that there will and be)
, somewhere later in the string.We perform this procedure for every parenthesis-word, n amount of times that builds off the solutions of the previous.
Recursively, I return the next u_set, since I know that every iteration approaches closer solution.
The bad:
A lot of time is wasted checking for duplicates, even though it is O(1) to confirm a duplication.
Last updated