Print combinations of balanced parentheses
It's a nice solution!

One thing that might speed things up a little would be to use a Set; no need for the include? then. Just call to_a on it at the end (or don't, and return a Set - still fits the task).

Also, I'd use p.length.times { |i| ... } instead of a for loop, and make a couple of variable names a little more descriptive (p, for instance, is not a very descriptive name).

require 'set'

def brackets(n)
  return ["()"] if n == 1

  brackets(n-1).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set &lt;&lt; str.dup.insert(i, "()")
    end
  end.to_a
end


Or, without converting to an array:

def brackets(n)
  return Set.new(["()"]) if n == 1

  brackets(n-1).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set &lt;&lt; str.dup.insert(i, "()")
    end
  end
end

brackets(3) # =&gt; #&lt;Set: {"()()()", "(())()", "()(())", "(()())", "((()))"}&gt;


Might also be nice to avoid the duplicated "()" string. You could make it an argument, so the method can be used for other "pairs", e.g:

def brackets(n, pair = "()")
  return Set.new([pair]) if n == 1

  brackets(n-1, pair).each_with_object(Set.new) do |str, set|
    str.length.times do |i|
      set &lt;&lt; str.dup.insert(i, pair)
    end
  end
end

brackets(3, "&lt;&gt;") # =&gt; #&lt;Set: {"&lt;&gt;&lt;&gt;&lt;&gt;", "&lt;&lt;&gt;&gt;&lt;&gt;", "&lt;&gt;&lt;&lt;&gt;&gt;", "&lt;&lt;&gt;&lt;&gt;&gt;", "&lt;&lt;&lt;&gt;&gt;&gt;"}&gt;


Or you can simply make it a constant, like SINGLE_PAIR = "()".freeze.