leetcode 823. Binary Trees With Factors(因子二叉树)

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 109 + 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] <= 109
All the values of arr are unique.

数组里面的数字可用来作树的节点,可以重复使用。
非叶子的节点的数字要等于它的children节点的乘积。
节点可以单独组成二叉树。

问可以组成多少个这样的二叉树。

思路:

首先想到的是要从小到大组成树,这样大的数字才能是小的数字的乘积,所以要把数组排序。

然后可以想到的是root的个数应该是左子树个数与右子树个数的乘积,
比如左子树有5种,右子树有6种,
那么左边的每一种都可以对应右边的6种,所以是乘法。

那么每次是不是都需要计算左右子树的个数?如果都计算,遇到重复的数字就会发生重复的计算,
所以要用DP,保存已经计算好的。

用dp[i]表示数字 ℹ 可以形成的二叉树个数。
每个数字可单独形成二叉树,所以dp[i] = 1。

arr[i]不是连续的数字,所以用hashMap作为dp数组,
从小到大遍历数字,遇到ℹ 是2个数乘积的,dp[i] += dp[左] * dp[右], 其中左 ✖ 右 = ℹ

最后把hashMap中的value相加。

注意相加时可能超出int的最大范围,所以用long, 不要忘了 % mod。

public int numFactoredBinaryTrees(int[] arr) {
    int n = arr.length;
    int mod = 1000000007;
    Long res = 0l;
    HashMap<Integer, Long> dp = new HashMap<>();
    
    Arrays.sort(arr);
    
    for(int i = 0; i < n; i ++) {  //arr下标
        dp.put(arr[i], 1l);
        for(int j = 0; j < i; j ++) {  //arr下标
            if(arr[i] % arr[j] == 0 && dp.containsKey(arr[i] / arr[j])) {
                dp.put(arr[i], (dp.get(arr[i]) + dp.get(arr[j]) * dp.get(arr[i]/arr[j]))%mod);
            }
        }
    }
    for(Long values : dp.values()) {
        res += values;
    }
    return (int)(res % mod);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值