leetcode - 823. Binary Trees With Factors

Description

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

Solution

Use dp, dp[i] = dp[j] * dp[k] + 1, for all j, k if j * k == i

Time complexity: o ( n 2 ) o(n^2) o(n2)

Space complexity: o ( n ) o(n) o(n)

Code

python3 复制代码
class Solution:
    def numFactoredBinaryTrees(self, arr: List[int]) -> int:
        dp = {each_num: 1 for each_num in arr}
        arr.sort()
        modulo = 1000000007
        for i in range(len(arr)):
            for j in range(i):
                if arr[i] % arr[j] == 0 and arr[i] // arr[j] in dp:
                    dp[arr[i]] += dp[arr[j]] * dp[arr[i] // arr[j]]
                    dp[arr[i]] %= modulo
        return sum(dp.values()) % modulo
相关推荐
CoovallyAIHub18 小时前
医药、零件、饮料瓶盖……SuperSimpleNet让质检“即插即用”
深度学习·算法·计算机视觉
dragoooon3418 小时前
[优选算法专题二滑动窗口——串联所有单词的子串]
数据结构·c++·学习·算法·leetcode·学习方法
刃神太酷啦18 小时前
C++ 异常处理机制:从基础到实践的全面解析----《Hello C++ Wrold!》(20)--(C/C++)
java·c语言·开发语言·c++·qt·算法·leetcode
Brookty18 小时前
【算法】双指针(二)复写零
学习·算法
胖达不服输19 小时前
「日拱一码」081 机器学习——梯度增强特征选择GBFS
人工智能·python·算法·机器学习·梯度增强特征选择·gbfs
初级炼丹师(爱说实话版)19 小时前
2025算法八股——深度学习——优化器小结
人工智能·深度学习·算法
努力的小帅19 小时前
C++_哈希
开发语言·c++·学习·算法·哈希算法·散列表
Christo320 小时前
TFS-2023《Fuzzy Clustering With Knowledge Extraction and Granulation》
人工智能·算法·机器学习·支持向量机
过河卒_zh156676620 小时前
AI内容标识新规实施后,大厂AI用户协议有何变化?(二)百度系
人工智能·算法·aigc·算法备案·生成合成类算法备案
薰衣草233320 小时前
滑动窗口(2)——不定长
python·算法·leetcode