我想做这个简单的计算,但它抱怨堆栈不够深,即使对于非常小的数字如n
,例如4.其他类似主题的SO帖子推荐尾部递归,但在这里不适用,因为只有在达到基本情况时才添加到累加值。递归时堆栈级别太深(SystemStackError)
RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}
def recursively_count_paths(x , y, n)
if x == n && y == n
return 1
puts " we got a path people"
elif x == n
puts "x is done"
return recursively_count_paths(x, y + 1, n)
elif y == n
puts "y is done"
return recursively_count_paths(x + 1, y, n)
else
return (recursively_count_paths(x + 1, y, n) +
recursively_count_paths(x, y + 1, n))
end
end
recursively_count_paths(0, 0, 20)
我不应该在其他情况下返回?
'puts'永远不会在第一个if条件下执行 – Ruslan
@Ruslan true。但这与问题是正交的。 – Thalatta
elsif而不是elif?我没有在RubyVM上运行这个,所以我不确定这会产生什么影响 –