缓存形式的实现
var memoize = function(fn) { var cache = []; return function(i) { return (i in cache) ? cache[i] : (cache[i] = fn.call(arguments.callee, i)); }; } var fib = new memoize(function(i) { if (i == 0 || i == 1) return 1; return this(i-1) + this(i-2); })
新的实现:
function fib(n) { function _fib(n, a, b, arg1, arg2) { if(n>1) _fib(n-1, a, b, arguments, arg1); return arg1[2] = arg2[1] = a+b; } return _fib(n, 0, 1, [], []); }