Search and backtracking · 10 / 15 Exercise Hard

Well-formed parentheses

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 n between 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 * n characters, 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.
Input
3
Output
((()))
(()())
(())()
()(())
()()()
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