[2, 4]
, we can form the trees 2
and 4(2,2)
.(x, y)
such that x * y = element
.dp
where dp[x]
represents the number of binary trees with root x
.dp[x]
to 1 to account for the single node tree.(a, b)
such that a * b = element
.
a
and b
(dp[a] * dp[b]
).dp[element]
.dp
dictionary modulo 10^9 + 7
.def numFactoredBinaryTrees(arr):
MOD = 10**9 + 7
arr.sort()
dp = {}
for num in arr:
dp[num] = 1 # Each number can at least form a single node tree by itself.
for i, num in enumerate(arr):
for j in range(i):
if num % arr[j] == 0: # arr[j] is the left child
right = num // arr[j]
if right in dp:
dp[num] = (dp[num] + dp[arr[j]] * dp[right]) % MOD
return sum(dp.values()) % MOD
# Example usage
arr = [2, 4, 5, 10]
print(numFactoredBinaryTrees(arr)) # Output: 7
O(n log n)
, where n
is the length of the array.n
, resulting in a nested loop which is O(n^2)
.O(n^2)
due to the nested loop after sorting.This approach efficiently calculates the number of binary trees with factors using dynamic programming while adhering to the constraints and providing an optimal solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?