zoukankan      html  css  js  c++  java
  • 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 + sumlimits_jdp[j] imes 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;
        }
    }
    
  • 相关阅读:
    解决网页元素无法定位的几种方法
    转载:pycharm最新版新建工程没导入本地包问题:module 'selenium.webdriver' has no attribute 'Firefox'
    关于list的漏删
    春风十里不如你
    记我兵荒马乱的一周(0808-0812)--用户反馈及修改点验证
    vue定时器
    业务系统多机房多活实现思路
    分布式开发之:id生成器
    关于部署系统的一些思考
    web系统认证与鉴权中的一些问题
  • 原文地址:https://www.cnblogs.com/mapoos/p/14530143.html
Copyright © 2011-2022 走看看