diff --git a/problems/22-generate-parentheses/main.rb b/problems/22-generate-parentheses/main.rb new file mode 100644 index 0000000..7f9d572 --- /dev/null +++ b/problems/22-generate-parentheses/main.rb @@ -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 diff --git a/problems/22-generate-parentheses/readme.md b/problems/22-generate-parentheses/readme.md new file mode 100644 index 0000000..1a6a399 --- /dev/null +++ b/problems/22-generate-parentheses/readme.md @@ -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 +``` diff --git a/problems/22-generate-parentheses/test.rb b/problems/22-generate-parentheses/test.rb new file mode 100644 index 0000000..dbbe2f6 --- /dev/null +++ b/problems/22-generate-parentheses/test.rb @@ -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