【发布时间】:2014-07-29 22:54:14
【问题描述】:
我正在尝试解决 10 秒超时限制的问题(如果函数运行时间超过 10 秒,则代码被视为“不正确”)。问题是给定一个整数(n),在总和为n的情况下,数字1和2的唯一可能组合有多少?
例如:n = 3,组合包括 [1, 1, 1] [1, 2] [2, 1]
我的代码是“正确的”,但对于编译器来说运行速度太慢并且被标记为不正确。我怎样才能让我的代码更有效率,为什么它“慢”?另外,需要注意的是,n 永远不会超过 1000。
require 'benchmark'
def stairs(n)
possible_combos = []
((n/2)..n).each do |i|
[1,2].repeated_permutation(i) do |combo|
if combo.inject {|sum, num| sum + num } == n
possible_combos << combo
end
end
end
puts possible_combos.uniq.length
end
puts Benchmark.measure {stairs(10)}
#=> 0.000000 0.000000 0.000000 ( 0.003864)
puts Benchmark.measure {stairs(20)}
#=> 5.720000 0.040000 5.760000 ( 5.762111)
【问题讨论】:
-
问题不清楚。为什么
[1, 2]和[2, 1]要分开计算? -
这是因为它们是独立的数组; [1,2] != [2,1]
标签: ruby performance big-o benchmarking permutation