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
相关推荐
喇一渡渡3 分钟前
Java力扣---滑动窗口(2)
算法·leetcode·职场和发展
面试鸭6 分钟前
华为开奖,还能a吗?
计算机·职场和发展·互联网
智驱力人工智能6 分钟前
山区搜救无人机人员检测算法 技术攻坚与生命救援的融合演进 城市高空无人机人群密度分析 多模态融合无人机识别系统
人工智能·深度学习·算法·架构·无人机·边缘计算
郝学胜-神的一滴19 分钟前
OpenGL中的glDrawArrays函数详解:从基础到实践
开发语言·c++·程序人生·算法·游戏程序·图形渲染
_OP_CHEN20 分钟前
【算法基础篇】(三十四)图论基础深度解析:从概念到代码,玩转图的存储与遍历
算法·蓝桥杯·图论·dfs·bfs·算法竞赛·acm/icpc
王璐WL28 分钟前
【数据结构】栈和队列及相关算法题
数据结构·算法
麒qiqi28 分钟前
Linux 线程(POSIX)核心教程
linux·算法
Zhi.C.Yue30 分钟前
React 的桶算法详解
前端·算法·react.js
小热茶32 分钟前
浮点数计算专题【五、 IEEE 754 浮点乘法算法详解---基于RISCV的FP32乘法指令在五级流水线的运行分析与SystemC实现】
人工智能·嵌入式硬件·算法·systemc
Giser探索家33 分钟前
卫星遥感数据核心参数解析:空间分辨率与时间分辨率
大数据·图像处理·人工智能·深度学习·算法·计算机视觉