xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

fibonacci all in one

fibonacci all in one

fibonacci sequence

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

fibonacci number

https://en.wikipedia.org/wiki/Fibonacci_number

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-09-30
 * @modified
 *
 * @description fibonacci all in one
 * @difficulty Easy
 * @complexity O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13757617.html
 * @link https://www.freecodecamp.org/learn/ fibo
 * @link https://www.freecodecamp.org/learn/coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

// 1. 递归

// 2. 迭代

// 3. 性能优化 cache



1. 递归

fibonacci 递归

// 1. 递归
function fibonacci(n) {
  if(n > 0) {
    if (n === 1 || n === 2) {
      return 1;
    } else {
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
  } else {
    throw new Error(`N must bigger than 0!`);
  }
}

``

## 2. 迭代 

> fibonacci 迭代

```js
// 2. 迭代 
function fibonacci(n) {
  if (n === 1 || n === 2) {
    return 1;
  } else {
    let sum = 2;
    let temp1 = 1;
    let temp2 = 1;
    while(n > 2) {
      sum = temp1 + temp2;
      // swap
      temp1 = temp2;
      temp2 = sum;
      n--;
    }
    return sum;
  }
}

3. 性能优化 cache

fibonacci memory 缓存优化

// 性能优化 cache
function fibonacci(n, memo) {
  if(n < 0) {
    throw new Error(`N must bigger than 0!`);
  }
  var memo = memo || {}
  // ReferenceError: Cannot access 'memo' before initialization
  // let memo = memo || {}
  if (memo[n]) {
    return memo[n];
  }
  if (n <= 2) {
    return 1;
  }
  // if (n <= 1) {
  //   return 1;
  // }
  return memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
}


fibonacci sequence vs 杨辉三角

https://zh.wikipedia.org/wiki/杨辉三角形

杨辉三角形,又称帕斯卡三角形、贾宪三角形、海亚姆三角形、巴斯卡三角形,是二项式系数的一种写法,形似三角形;

在中国首现于南宋杨辉的《详解九章算法》得名,书中杨辉说明是引自贾宪的《释锁算书》,故又名贾宪三角形。前 9 行写出来如下:

        1
       1 1
      1 2 1
     1 3 3 1
    1 4 6 4 1
   1 5 10 10 5 1
  1 6 15 20 15 6 1
 1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1

refs

https://www.cnblogs.com/xgqfrms/p/12909516.html



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-10-01 12:28  xgqfrms  阅读(125)  评论(0编辑  收藏  举报