Java recursive dp solution beats 100% || hashmap
\nclass Solution {\n     public int numFactoredBinaryTrees(int[] arr) {\n        int n = arr.length;\n        long[] dp = new long[n];\n        long ans = 0;\n 
```\nclass Solution {\n     public int numFactoredBinaryTrees(int[] arr) {\n        int n = arr.length;\n        long[] dp = new long[n];\n        long ans = 0;\n        Arrays.fill(dp, -1);\n        Arrays.sort(arr);\n        int mod = (int) (1e9 + 7);\n        HashMap<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < n; i++) map.put(arr[i], i);\n        for (int i = 0; i < n; i++) {\n            ans = ((ans % mod) + (countTreesWithRoot(i, map, dp, arr, mod) % mod)) % mod;\n        }\n        return (int) ans;\n    }\n\n    private long countTreesWithRoot(int i, HashMap<Integer, Integer> map, long[] dp, int[] arr, int mod) {\n        if (dp[i] != -1) return dp[i];\n        int node_val = arr[i];\n        long ans = 1;\n        for (int j = 0; j < arr.length; j++) {\n            if (arr[j] > Math.sqrt(node_val)) break;\n            if (node_val % arr[j] == 0 && map.containsKey(node_val / arr[j])) {\n                long leftWays = countTreesWithRoot(j, map, dp, arr, mod);\n                long rightWays = countTreesWithRoot(map.get(node_val / arr[j]), map, dp, arr, mod);\n                long res = ((leftWays % mod) * (rightWays % mod)) % mod;\n                res = (res % mod) * (arr[j] == node_val / arr[j] ? 1 : 2);\n                ans = (ans % mod + res % mod) % mod;\n            }\n        }\n        return dp[i] = ans % mod;\n    }\n}\n```
['Dynamic Programming', 'Recursion', 'Java']