Last active
March 23, 2017 16:40
-
-
Save liuderchi/287cabfaa2c8ccd873dd5f7a39f31a0a to your computer and use it in GitHub Desktop.
Dynamic Programming Basic example
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
// http://www.csie.ntnu.edu.tw/~u91029/DynamicProgramming.html#2 | |
function stairs(n) { | |
var res = []; | |
res[0] = 1; // first stair | |
res[1] = 1; // second stair | |
if (n > 0 && n < 2) return res[n-1]; | |
for (var i = 2; i < n; i++){ | |
res[i] = res[i-1] + res[i-2]; // linear space | |
} | |
return res[n-1]; | |
} | |
console.log(stairs(1)); // 1 | |
console.log(stairs(2)); // 1 | |
console.log(stairs(5)); // 5 | |
function factorial(x) { | |
var res = []; | |
res[0] = 1; | |
res[1] = 1; | |
if (x >= 0 && x < 2) return res[x]; | |
for (var i = 2; i < x+1; i++){ | |
res[i] = res[i-1] * i; | |
} | |
return res[x]; | |
} | |
console.log(factorial(0)); // 1 | |
console.log(factorial(1)); // 1 | |
console.log(factorial(5)); // 120 | |
console.log(factorial(7)); // 5040 | |
console.log(factorial(10)); // 3628800 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment