Created
October 19, 2015 21:24
-
-
Save sahas-/b65e07945c89179387b0 to your computer and use it in GitHub Desktop.
This file contains 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
-- | |
Recursive: go thru recursion everytime. | |
class test{ | |
fib(n: number){ | |
if (n<= 2) return 1; | |
return this.fib(n-1) + this.fib(n-2); | |
} | |
} | |
var f = new test() | |
console.log(f.fib(10)); | |
console.log(f.fib(14)); | |
--- | |
Memorization: go thru recursion once, store it in cache and respond before going thru next time.. | |
export class test{ | |
memo=[]; | |
fib(n: number){ | |
if (this.memo[n] != undefined) return this.memo[n]; | |
if (n<=2) return 1; | |
for (var i=3;i<=n;i++){ | |
var f = this.fib(i-1) + this.fib(i-2); | |
this.memo[i] = f; | |
} | |
return this.memo[n]; | |
} | |
} | |
var a = new test(); | |
console.log(a.fib(10)); | |
console.log(a.fib(55)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment