Created
April 18, 2022 11:35
-
-
Save jps/88eb65458d202d27cec25f25a486c1d7 to your computer and use it in GitHub Desktop.
fibonachi implementation with backtracking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = require('assert'); | |
| const fib = (n: number, memo?: Array<number>): number => { | |
| if (memo == null) { | |
| memo = Array(n); | |
| } | |
| if (memo[n] === undefined) { | |
| memo[n] = n == 0 || n == 1 | |
| ? 1 | |
| : fib(n - 1, memo) + fib(n - 2, memo); | |
| } | |
| return memo[n]; | |
| }; | |
| //1,1,2,3,5,8,13 | |
| assert.equal(1, fib(0)); | |
| assert.equal(1, fib(1)); | |
| assert.equal(2, fib(2)); | |
| assert.equal(3, fib(3)); | |
| assert.equal(5, fib(4)); | |
| assert.equal(8, fib(5)); | |
| assert.equal(13, fib(6)); | |
| assert.equal(3524578, fib(32)); | |
| assert.equal(165580141, fib(40)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment