Algorithms 1 min read

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Solution:
# @param {Integer} n
# @return {String[]}
def generate_parenthesis(n, left=0, right=0, current="", result=[])
    if current.length == n*2
        result << current
        return
    end

    generate_parenthesis(n, left + 1, right, current + "(", result) if left < n
    generate_parenthesis(n, left, right + 1, current + ")", result) if right < left

    result
end
 




 

Related Posts