Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created June 24, 2020 07:30
Show Gist options
  • Save RP-3/f880522e6418c4bf92f776835f6f5fe3 to your computer and use it in GitHub Desktop.
Save RP-3/f880522e6418c4bf92f776835f6f5fe3 to your computer and use it in GitHub Desktop.
/**
* @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