823. Binary Trees With Factors

Given an array of unique integers, each integer is strictly greater than 1.

We make a binary tree using these integers and each number may be used for any number of times.

Each non-leaf node's value should be equal to the product of the values of it's children.

How many binary trees can we make?  Return the answer modulo 10 ** 9 + 7.

Example 1:

Input: A = [2, 4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]

Example 2:

Input: A = [2, 4, 5, 10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].

 

Note:

  1. 1 <= A.length <= 1000.
  2. 2 <= A[i] <= 10 ^ 9.

很明显的DP,自己最开始为什么想到其他地方去了?

从子树往前搜索是不行的,树的遍历不都是从root开始往下么?

class Solution:
    def numFactoredBinaryTrees(self, a):
        """
        :type A: List[int]
        :rtype: int
        """
        a.sort()
        s=set(a)
        a=list(s)
        a.sort()
        d={}
        for i,v in enumerate(a):
            d[v]=i
        
        dp = [1]*len(a)
        for i in range(1,len(a)):
            for j in range(i):
                if a[i]%a[j]==0 and a[i]//a[j] in s:
#                    t = 1 if a[j]*a[j]==a[i] else 2
                    t = 1
                    dp[i] += t*dp[j]*dp[d.get(a[i]//a[j])]
                    dp[i] %= 1000000007
        return sum(dp)%1000000007
    
s=Solution()
print(s.numFactoredBinaryTrees([2, 4]))
print(s.numFactoredBinaryTrees([2, 4, 5, 10]))
print(s.numFactoredBinaryTrees([45,42,2,18,23,1170,12,41,40,9,47,24,33,28,10,32,29,17,46,11,759,37,6,26,21,49,31,14,19,8,13,7,27,22,3,36,34,38,39,30,43,15,4,16,35,25,20,44,5,48]))

                

比如下面这样从子树推root是错的,因为在用d[10]的时候,可能有其他的组合使得d[10]还可以更大

class Solution:
    def numFactoredBinaryTrees(self, a):
        """
        :type A: List[int]
        :rtype: int
        """
        a.sort()
        s=set(a)
        a=list(s)
        a.sort()
        d={}
        for i,v in enumerate(a):
            d[v]=i
        
        dp = [1]*len(a)
        for i in range(1,len(a)):
            for j in range(i):
                if a[i]%a[j]==0 and a[i]//a[j] in s:
#                    t = 1 if a[j]*a[j]==a[i] else 2
                    t = 1
                    dp[i] += t*dp[j]*dp[d.get(a[i]//a[j])]
                    dp[i] %= 1000000007
        return sum(dp)%1000000007
    
s=Solution()
print(s.numFactoredBinaryTrees([2, 4]))
print(s.numFactoredBinaryTrees([2, 4, 5, 10]))
print(s.numFactoredBinaryTrees([45,42,2,18,23,1170,12,41,40,9,47,24,33,28,10,32,29,17,46,11,759,37,6,26,21,49,31,14,19,8,13,7,27,22,3,36,34,38,39,30,43,15,4,16,35,25,20,44,5,48]))

                

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/80037643
今日推荐