Search code examples
pythonpermutation

How to generate all valid permutations of parentheses in Python?


I want to generate all possible permutations of a set of parentheses of a certain length N.

Example:

if N = 1
Output: ['()']

if N = 3
Output: ['()(())', '(())()', '(()())', '((()))', '()()()']

Solution

  • Credit: https://prepinsta.com/python-program/generate-all-combinations-of-balanced-parentheses/

    def generateParenthesis(n, Open, close, s, ans):
    
        if Open == n and close == n:
            ans.append(s)
            return
    
        if Open < n:
            generateParenthesis(n, Open + 1, close, s + "(", ans)
    
        if close < Open:
            generateParenthesis(n, Open, close + 1, s + ")", ans)
    
    
    n = 3
    ans = []
    generateParenthesis(n, 0, 0, "", ans)
    for s in ans:
        print(s)