1
/** https://leetcode.com/problems/binary-trees-with-factors/2
* @param {number[]} arr5
var numFactoredBinaryTrees = function (arr) {10
arr.sort((a, b) => a - b);12
// Create hashmap so we can easily find the index of the value14
arr.forEach((val, idx) => map.set(val, idx));16
// We are going to calculate total numbers of binary trees by assigning each `arr[i]` as the root of the tree18
for (let i = arr.length - 1; i >= 0; i--) {19
count += dp(arr, map, i);22
// Perform mod on the final result23
let mod = 10 ** 9 + 7;27
var dp = function (arr, map, currIdx) {29
if (this.memo.has(currIdx) === true) {30
return this.memo.get(currIdx);33
// Start the count as 1 to include the current node36
// Loop through all number before `arr[currIdx]`37
for (let i = currIdx - 1; i >= 0; i--) {38
// The `left` and `right` node of the root39
// The `right` node is basically the root divided by the `left` since the rule stated that the root is product of its children41
let right = arr[currIdx] / left;43
// Ignore if the root is not a product of its children44
if (arr[currIdx] % left !== 0 || map.has(right) === false) {48
// Get the count for `left` node and `right` node49
let leftCount = dp(arr, map, i);50
let rightCount = dp(arr, map, map.get(right));52
// Total count is multiplication of `left` and `right` count because each combination of is unique53
count += leftCount * rightCount;57
this.memo.set(currIdx, count);