等我写完发现,知乎上都比我写的好,我快哭了!!!
等我写完之后发现不就是那啥啥函数,贴上lua代码
N很大的时候,估计是抗不住了,代码还需要优化。
function banana( n ) local c = 1; if n == 0 then return 0 elseif n == 1 then return 1 elseif n == 2 then return 2 end return (banana(n - 1) + banana(n - 2)) * c; end for i = 1, 10 do print(banana(i)) end
优化后的代码:
local know = {} function banana( n ) if know[n] then return know[n] end local c = 1; if n == 0 then know[n] = 0 return 0 elseif n == 1 then know[n] = 1 return 1 elseif n == 2 then know[n] = 2 return 2 end local r = (banana(n - 1) + banana(n - 2)) * c; know[n] = r return r end for i = 1, 50 do print(i, banana(i)) end
时间: 2024-10-20 10:11:53