斐波那契数列<递归和排序>
算法(斐波那契数列两种方法分析)
// 递归方法 let data1 = new Date(); function fib(n) { if (n === 1 || n === 2) return n - 1 return fib(n - 1) + fib(n - 2) } let arr = [] for (let index = 1; index < 10 ; index++) { arr.push(fib(index)) } let data2 = new Date(); console.log(arr, data2 - data1); //非递归方法 let data3 = new Date(); function fib1(n) { if (n == 1) { return 0 } let a = 0 let b = 1 let c = a + b for (let i = 3; i < n; i++) { a = b b = c c = a + b } return c } let arr1 = [] for (let index = 1; index < 10; index++) { arr1.push(fib1(index)) } let data4 = new Date(); console.log(arr1, data4 - data3);
递归优化存已经算过的值
var temp = [] var climbStairs = function(n) { if(n <= 0){ return 0 } if(n <= 2){ return n } if(temp[n]){ return temp[n] } temp[n] = climbStairs(n-2) + climbStairs(n-1) return temp[n] }; console.log(climbStairs(10));