function fbnq(n) { if(n == 1 || n == 2) { return 1 } return fbnq(n - 1) + fbnq(n - 2) } for(var i=10;0<i;i--){ console.log(fbnq(i)) }
缓存的写法 --- 减少递归次数,防止爆栈
// 缓存 let cache = {} function fbnq(n) { if(n == 1 || n == 2) { return 1 } if(cache.hasOwnProperty(n)) { return cache[n] } cache[n] = fbnq(n - 1) + fbnq(n - 2) return cache[n] } for(var i=10;0<i;i--){ console.log(fbnq(i)) }
变量局部化
// 缓存 class Cache { constructor(n) { this.cache = {} } init(n) { if(n == 1 || n == 2) { return 1 } if(this.cache.hasOwnProperty(n)) { return this.cache[n] } this.cache[n] = this.init(n - 1) + this.init(n - 2) return this.cache[n] } } let fbnq = new Cache() for(var i=10;0<i;i--){ console.log(fbnq.init(i)) } console.log(fbnq.cache)
不用递归的写法
var arr = [1,1] while(arr.length < 10) { arr.push(arr[arr.length - 1] + arr[arr.length - 2]) }
标签:10,arr,return,递归,cache,fbnq,var From: https://www.cnblogs.com/caijinghong/p/16916459.html