LeetCode: Binary Trees With Factors Solution
Approach
Multiplying as result of combination
Implementation
1/**2 * @param {number[]} arr3 * @return {number}4 */5var numFactoredBinaryTrees = function (arr) {6 const set = new Set(arr)7 const memo = new Map()8 const recursion = el => {9 if (memo.has(el)) {10 return memo.get(el)11 }12 let count = 113 for (const otherEl of arr) {14 if (el % otherEl === 0 && set.has(el / otherEl)) {15 count += recursion(otherEl) * recursion(el / otherEl)16 }17 }18 memo.set(el, count)19 return count20 }2122 return arr.reduce((acc, el) => (acc += recursion(el)), 0) % (1e9 + 7)23}
Comments
Loading comments...
Tags
leetcode
recursion
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.