-1

Given a number of brackets pairs. I want to display all correct combinations of these brackets. By correct I mean each bracket should be opened before closing in each combination. For example, if the number of brackets is 2 the output should be:

(())
()()

For 3:

((()))
()()()
(()())
(())()
()(())

The order of the output lines doesn't matter.

How can I do it with Python?

Daronna
  • 31
  • 7
  • 5
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/questions/how-to-ask). – TigerhawkT3 Dec 21 '16 at 05:51
  • @TigerhawkT3 When did you write this first 20..? :D – Mohammad Yusuf Dec 21 '16 at 05:58
  • @MohammadYusufGhazi - I started using it this year, but it's been pretty common around here for quite some time. Feel free to copy it. – TigerhawkT3 Dec 21 '16 at 06:06
  • Two terminology notes: (1) The characters "(" and ")" in programming are known as parentheses, not brackets; brackets are "[" and "]"; (2) in the first example, you have 2 _pairs_ of parentheses, not 2 parentheses. – DYZ Dec 21 '16 at 06:21
  • This is problem 8.9 in chapter 8 of the book `Cracking the Coding Interview` 6th edition -- the book has a program to do this. – Marichyasana Dec 21 '16 at 08:09
  • I've written a new compact answer for this problem at http://stackoverflow.com/a/41310973/4014959 There's all sorts of interesting information relating to Catalan numbers at http://oeis.org/A000108 – PM 2Ring Dec 24 '16 at 06:40

1 Answers1

0

Try this code, please:

def __F(l, r, pref):
    if r < l or l < 0 or r < 0:
        return
    if r == 0 and l == 0:
        print(pref)
        return
    __F(l - 1, r, pref + "(")
    __F(l, r - 1, pref + ")")

def F(n):
    __F(n, n, "")

F(2)
F(3)
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95