mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
add generate_parenthesis backtracking approach
This commit is contained in:
parent
515b076e61
commit
13aec345ea
1 changed files with 47 additions and 0 deletions
47
backtracking/generate_paranthesis.rb
Normal file
47
backtracking/generate_paranthesis.rb
Normal file
|
@ -0,0 +1,47 @@
|
|||
# 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: ["()"]
|
||||
#
|
||||
#
|
||||
# Constraints:
|
||||
#
|
||||
# 1 <= n <= 8
|
||||
|
||||
# @param {Integer} n
|
||||
# @return {String[]}
|
||||
def generate_parenthesis(n)
|
||||
parenthesis = []
|
||||
backtrack(parenthesis, "", 0, 0, n)
|
||||
parenthesis
|
||||
end
|
||||
|
||||
def backtrack(parenthesis, curr, open, close, max)
|
||||
if curr.length == max * 2
|
||||
parenthesis.push(curr)
|
||||
return
|
||||
end
|
||||
|
||||
if open < max
|
||||
backtrack(parenthesis, curr + "(", open + 1, close, max)
|
||||
end
|
||||
|
||||
if close < open
|
||||
backtrack(parenthesis, curr + ")", open, close + 1, max)
|
||||
end
|
||||
end
|
||||
|
||||
n = 3
|
||||
print(generate_parenthesis(n))
|
||||
# Output: ["((()))","(()())","(())()","()(())","()()()"]
|
||||
|
||||
n = 1
|
||||
print(generate_parenthesis(n))
|
||||
# Output: ["()"]
|
Loading…
Reference in a new issue