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
相关推荐
Xの哲學5 分钟前
Linux自旋锁深度解析: 从设计思想到实战应用
linux·服务器·网络·数据结构·算法
晚风吹长发9 分钟前
深入理解Linux中用户缓冲区,文件系统及inode
linux·运维·算法·链接·缓冲区·inode
程序员-King.17 分钟前
day131—链表—反转链表Ⅱ(区域反转)(LeetCode-92)
leetcode·链表·贪心算法
cwplh18 分钟前
DP 优化一:单调队列优化 DP
算法
Halo_tjn19 分钟前
基于Java的相关知识点
java·开发语言·windows·python·算法
CoovallyAIHub23 分钟前
英伟达CES 2026炸场:没有新显卡,却掏出了让全球AI公司彻夜难眠的“算力核弹”
深度学习·算法·计算机视觉
圣保罗的大教堂25 分钟前
leetcode 2943. 最大化网格图中正方形空洞的面积 中等
leetcode
独自破碎E44 分钟前
包含min函数的栈
android·java·开发语言·leetcode
wregjru44 分钟前
【C++】2.9异常处理
开发语言·c++·算法
CoovallyAIHub1 小时前
如何用10%的标注数据,达到可媲美全监督模型的性能?AAAI 2026论文揭秘BCSI三大创新设计
深度学习·算法·计算机视觉