Skip to content

Commit ab16c9a

Browse files
committed
Create binary-trees-with-factors.py
1 parent 375ccd6 commit ab16c9a

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Time: O(n^2)
2+
# Space: O(n)
3+
4+
# Given an array of unique integers, each integer is strictly greater than 1.
5+
# We make a binary tree using these integers and each number may be used for
6+
# any number of times.
7+
# Each non-leaf node's value should be equal to the product of the values of
8+
# it's children.
9+
# How many binary trees can we make? Return the answer modulo 10 ** 9 + 7.
10+
#
11+
# Example 1:
12+
#
13+
# Input: A = [2, 4]
14+
# Output: 3
15+
# Explanation: We can make these trees: [2], [4], [4, 2, 2]
16+
# Example 2:
17+
#
18+
# Input: A = [2, 4, 5, 10]
19+
# Output: 7
20+
# Explanation: We can make these trees:
21+
# [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
22+
#
23+
# Note:
24+
# - 1 <= A.length <= 1000.
25+
# - 2 <= A[i] <= 10 ^ 9.
26+
27+
try:
28+
xrange # Python 2
29+
except NameError:
30+
xrange = range # Python 3
31+
32+
33+
class Solution(object):
34+
def numFactoredBinaryTrees(self, A):
35+
"""
36+
:type A: List[int]
37+
:rtype: int
38+
"""
39+
M = 10**9 + 7
40+
A.sort()
41+
dp = {}
42+
for i in xrange(len(A)):
43+
dp[A[i]] = 1
44+
for j in xrange(i):
45+
if A[i] % A[j] == 0 and A[i] // A[j] in dp:
46+
dp[A[i]] += dp[A[j]] * dp[A[i] // A[j]]
47+
dp[A[i]] %= M
48+
return sum(dp.values()) % M

0 commit comments

Comments
 (0)