Binary Trees With Factors LeetCode solution in Java
1class Solution {2int mod = 1000000007;3HashMap<Integer, Long> dp;4HashSet<Integer> set;56public int numFactoredBinaryTrees(int[] arr) {7long ans = 0;8dp = new HashMap<>();9set = new HashSet<>();1011for (int val : arr) set.add(val);1213for (int val : arr) {14// giving each unique value a chance to be root node of the tree15ans += solve(val, arr);16ans %= mod;17}1819return (int) ans;20}2122public long solve(int val, int[] nums) {2324if (dp.containsKey(val)) {25return dp.get(val);26}2728long ans = 1;2930for (int i = 0; i < nums.length; i++) {31if (val % nums[i] == 0 && set.contains(val / nums[i])) {32long left = solve(nums[i], nums);33long right = solve(val / nums[i], nums);3435ans += ((left * right) % mod);36ans %= mod;37}38}3940dp.put(val, ans);4142return ans;43}44}