Objective
Create a Python program that generates all the strings of well-formed parentheses with n pairs. With pruning, only valid branches are built: a parenthesis that is not open is never closed.
Instructions
- Read an integer
nbetween 1 and 5. - Write a recursive function that keeps the current text and how many parentheses have been opened and closed. When the text has
2 * ncharacters, it stores it. At each step, first add"("if there are still some left to open (opened < n) and then add")"if there are more open than closed. - Show each string on a line, in the order they are generated, and finish with
Total: t.
3
((()))
(()())
(())()
()(())
()()()
Total: 5
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise