0823. Binary Trees With Factors (M)

Binary Trees With Factors (M)

题目

Given an array of unique integers, arr, where each integer arr[i] 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 its children.

Return the number of binary trees we can make. The answer may be too large so return the answer modulo 10^9 + 7.

Example 1:

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

Example 2:

Input: arr = [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].

Constraints:

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

题意

给定一个包含不同数字的数组,用其中的任意个数字组成一个二叉树,是这个二叉树满足每一个非叶子父结点的值都是两个子结点的值的积,问有多少个这样的二叉树。

思路

动态规划。我们将所有数从小到大排序,将其依次作为根结点,求出对应的二叉树的个数,最终求和就是答案。具体方法为:以数i作为根结点时,找到所有数j,使得i是j的倍数且i/j也在数组中,那么\(dp[i]=1 + \sum\limits_jdp[j]\times dp[i/j]\)


代码实现

Java

class Solution {
    public int numFactoredBinaryTrees(int[] arr) {
        long sum = 0;
        Map<Integer, Long> map = new HashMap<>();
        Arrays.sort(arr);
      
        for (int i = 0; i < arr.length; i++) {
            long cnt = 1;
            for (int j = 0; j < i; j++) {
                if (arr[i] % arr[j] == 0 && map.containsKey(arr[i] / arr[j])) {
                    cnt += map.get(arr[j]) * map.get(arr[i] / arr[j]) % 1000000007;
                }
            }
            map.put(arr[i], cnt);
            sum = (sum + cnt) % 1000000007;
        }
      
        return (int) sum;
    }
}
posted @ 2021-03-13 19:53  墨云黑  阅读(52)  评论(0编辑  收藏  举报