Problem 22: generate parentheses

This commit is contained in:
Ivan R. 2022-12-25 10:42:11 +05:00
parent ed6bb14c07
commit 3129bbecc5
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
3 changed files with 94 additions and 0 deletions

View file

@ -0,0 +1,40 @@
# Naive bruteforce solution
# @param {Integer} n
# @return {String[]}
def generate_parenthesis(n)
combinations = ['(']
# Generate an array of all possible combinations
(2..n * 2).each do |i|
new_iteration = []
combinations.each do |elem|
new_iteration.push("#{elem})")
# Opening bracket can't be the last one
new_iteration.push("#{elem}(") if i != n * 2
end
combinations = new_iteration
end
# Return only valid combinations
combinations.select { |l| parenthesis_valid?(l) }
end
def parenthesis_valid?(s)
open_brackets = 0
s.each_char do |char|
if char == '('
open_brackets += 1
else
open_brackets -= 1
end
return false if open_brackets.negative?
end
return false if open_brackets.positive?
true
end

View file

@ -0,0 +1,23 @@
# 22. 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: ["()"]
```
## Constraints:
```
1 <= n <= 8
```

View file

@ -0,0 +1,31 @@
require_relative 'main'
require 'test/unit'
class TestParenthesesGenerator < Test::Unit::TestCase
def test_one_level
res = generate_parenthesis(1)
assert_equal(['()'], res)
end
def test_three_levels
res = generate_parenthesis(3)
out = %w[((())) (()()) (())() ()(()) ()()()]
out.each do |p|
assert(res.include?(p), "Missing: #{p}")
end
assert_equal(out.count, res.count)
end
def test_five_levels
res = generate_parenthesis(5)
out = %w[((((())))) (((()()))) (((())())) (((()))()) (((())))() ((()(()))) ((()()())) ((()())()) ((()()))() ((())(())) ((())()()) ((())())() ((()))(()) ((()))()() (()((()))) (()(()())) (()(())()) (()(()))() (()()(())) (()()()()) (()()())() (()())(()) (()())()() (())((())) (())(()()) (())(())() (())()(()) (())()()() ()(((()))) ()((()())) ()((())()) ()((()))() ()(()(())) ()(()()()) ()(()())() ()(())(()) ()(())()() ()()((())) ()()(()()) ()()(())() ()()()(()) ()()()()()]
out.each do |p|
assert(res.include?(p), "Missing: #{p}")
end
assert_equal(out.count, res.count)
end
end