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
相关推荐
Musennn1 小时前
leetcode 15.三数之和 思路分析
算法·leetcode·职场和发展
CM莫问4 小时前
<论文>(微软)避免推荐域外物品:基于LLM的受限生成式推荐
人工智能·算法·大模型·推荐算法·受限生成
康谋自动驾驶4 小时前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈5 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java6 小时前
R-tree详解
java·算法·r-tree
MarkHard1236 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
一只鱼^_7 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼7 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程7 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
↣life♚8 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割