#2 楼 @bluexuemei
a = [*0..9]
def c arr, n
return arr.map {|i| [i]} if n == 1
rets = []
arr.each_with_index do |ele, i|
rets += c(arr[i + 1, arr.size - i - 1], n - 1).map {|a| [ele, *a]}
end
rets
end
def all_sub_arrs arr
rets = []
1.upto(arr.size) do |i|
rets += c(arr, i)
end
rets
end
require 'benchmark'
Benchmark.bm do |x|
x.report do
result = []
1.upto(a.size) {|i| a.combination(i).each {|sub_arr| result << sub_arr.to_a}}
end
x.report {result = all_sub_arrs a}
end
自己实现 combination 肯定没有 ruby 自带的快,Array 内置的方法都是 c 写的。