1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { private static final int MOD = (int) 1e9 + 7; long[] cache; Map<Integer, Integer> map; int[] arr;
public int numFactoredBinaryTrees(int[] arr) { this.arr = arr; int n = arr.length; Arrays.sort(arr); map = new HashMap<>(n); for (int i = 0; i < n; ++i) map.put(arr[i], i); cache = new long[n]; Arrays.fill(cache, -1); long ans = 0; for (int i = 0; i < n; ++i) { ans += dfs(i); } return (int) (ans % MOD); }
private long dfs(int i) { if (cache[i] != -1) return cache[i]; int x = arr[i]; long ans = 1; for (int j = 0; j < i; ++j) { int y = arr[j]; if (x % y == 0 && map.containsKey(x / y)) { ans += dfs(j) * dfs(map.get(x / y)); } } return cache[i] = ans; } }
|