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
Share this post
Related Posts
Jump Game II
April 13, 2025
Longest Palindromic Substring
April 03, 2025
Choosing pivot in Quicksort
April 14, 2025