# 从斐波那契数列看递归和动态规划

### 递归

``````// 直接使用递归
let num = 0;    // 用来记录fib函数执行次数，执行一次加一
function fib(n) {
num ++;
if(n === 0) {
return 0;
}
if(n === 1) {
return 1;
}
return fib(n-1) + fib(n-2);
}

console.time("time used");
console.log(`result is: \${fib(40)}`);
console.log(`fib() runned \${num} times`);
console.timeEnd("time used");``````

### 记忆化搜索递归(自顶向下)

``````// 记忆化搜索，记录每次计算的结果
let num = 0; // 用来记录fib函数执行次数，执行一次加一
let totalnum = 40;
let memory = new Array(totalnum).fill(-1);
function fib(n) {
num++;
if(n === 0) {
return 0;
}
if(n === 1) {
return 1;
}
if(memory[n] === -1) {
memory[n] = fib(n-1) + fib(n-2);  // 如果前面已经得到，直接使用
}
return memory[n];
}

console.time("timer");
console.log(`result is: \${fib(totalnum)}`);
console.log(`fib() runned \${num} times`);
console.timeEnd("timer");``````

Dynamic programming is when you use past knowledge to make solving a future problem easier.(动态规划是用已知项去更好的求解未知项)

Dynamic programming is a technique used to avoid computing multiple time the same subproblem in a recursive algorithm.

### 迭代法(自下向上)

``````let num = 0;
function fib(n) {
num++;
let memory = new Array(n);
memory[0] = 1;
memory[1] = 1;
for(let i = 2; i <= n; i++) {
memory[i] = memory[i-1] + memory[i-2];
}
return memory[n];
}

console.time("timer");
console.log(`result is: \${fib(40)}`);
console.log(`fib() runned \${num} times`);
console.timeEnd("timer");``````

### 小结

原文作者：Leon
原文地址: https://segmentfault.com/a/1190000015489981
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。