【leetcode】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.

解题思路:假设i*j = k,记dp[k] 为 k作为树的根节点时可以构成的树的数量,那么有dp[k] = 1 + dp[i] * dp[j] (1 为树中只有一个根节点的情况),如果同时还有m*n = k,那么有dp[k] = 1 + dp[i] * dp[j] + dp[m]*dp[n],有了状态转移方程后,题目就很简单了。对A进行排序,这样可以保证k > i & k > j 如果A[k] = A[i] * A[j] 。接下来对A进行遍历,同时嵌套一层循环,如果满足A[i] * A[j] = A[k],就令dp[k] +=  dp[i] * dp[j]。最后的答案就是sum(dp)。

代码如下:

class Solution(object):
    def numFactoredBinaryTrees2(self, A):
        A.sort()
        dic = {}
        dp = [1] * len(A)
        for i in range(len(A)):
            dic[A[i]] = i
            for j in range(i):
                if A[i] % A[j] == 0 and A[i] / A[j] in dic:
                    v = A[i] / A[j]
                    dp[i] += dp[j] * dp[dic[v]]
        return sum(dp) % (10**9 + 7)

猜你喜欢

转载自www.cnblogs.com/seyjs/p/10565770.html