我想知道这个用于生成排列的函数的惯用版本在 Ruby 中会是什么样子。我知道这[1,2,3].permutation.to_a
会产生相同的结果,但我对学习 Ruby 以及如何在 Ruby 中处理这样的递归问题更感兴趣。
def permutations(seq)
if seq.empty? || seq.count == 1
seq
else
seq.map { |x|
permutations(seq.select { |e| e != x }).map { |p|
if p.class == Fixnum
[x, p]
else
p.unshift(x)
end
}
}.flatten(1)
end
end
谢谢!