Created
June 24, 2020 07:30
-
-
Save RP-3/f880522e6418c4bf92f776835f6f5fe3 to your computer and use it in GitHub Desktop.
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
/** | |
* @param {number} n | |
* @return {number} | |
*/ | |
var numTrees = function(n) { | |
const memo = new Array(n+1).fill(0).map(() => new Array(n+1).fill(-1)); | |
const count = (l, r) => { | |
if(r <= l) return 1; | |
if(memo[l][r] !== -1) return memo[l][r]; | |
let result = 0; | |
for(let i=l; i<=r; i++){ // for each val, lock it as the root | |
const leftTrees = count(l, i-1); // then count the number on the left | |
const rightTrees = count(i+1, r); // and the number on the right | |
result += (leftTrees * rightTrees); // multiply them together | |
} | |
return memo[l][r] = result; | |
}; | |
return count(1, n); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment