LeetCode 题解工作台
带因子的二叉树
给出一个含有不重复整数元素的数组 arr ,每个整数 arr[i] 均大于 1。 用这些整数来构建二叉树,每个整数可以使用任意次数。其中:每个非叶结点的值应等于它的两个子结点的值的乘积。 满足条件的二叉树一共有多少个?答案可能很大,返回 对 10 9 + 7 取余 的结果。 示例 1: 输入: ar…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以枚举 中的每一个数 作为二叉树的根节点(根节点一定最大),然后枚举枚举左子树的值 ,若 能被 整除,则右子树的值为 $a / b$,若 $a / b$ 也在 中,则可以构成一棵二叉树。此时,以 为根节点的二叉树的个数为 $f(a) = f(b) \times f(a / b)$,其中 和 $f(a / b)$ 分别为左子树和右子树的二叉树个数。 因此,我们先将 排序,然后用…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给出一个含有不重复整数元素的数组 arr ,每个整数 arr[i] 均大于 1。
用这些整数来构建二叉树,每个整数可以使用任意次数。其中:每个非叶结点的值应等于它的两个子结点的值的乘积。
满足条件的二叉树一共有多少个?答案可能很大,返回 对 109 + 7 取余 的结果。
示例 1:
输入:arr = [2, 4]输出: 3 解释: 可以得到这些二叉树:[2], [4], [4, 2, 2]
示例 2:
输入:arr = [2, 4, 5, 10]输出:7解释: 可以得到这些二叉树:[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
提示:
1 <= arr.length <= 10002 <= arr[i] <= 109arr中的所有值 互不相同
解题思路
方法一:动态规划
我们可以枚举 中的每一个数 作为二叉树的根节点(根节点一定最大),然后枚举枚举左子树的值 ,若 能被 整除,则右子树的值为 ,若 也在 中,则可以构成一棵二叉树。此时,以 为根节点的二叉树的个数为 ,其中 和 分别为左子树和右子树的二叉树个数。
因此,我们先将 排序,然后用 表示以 为根节点的二叉树的个数,最终答案即为 。注意答案可能很大,需要对 取模。
时间复杂度为 ,空间复杂度为 。其中 为 的长度。
class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
mod = 10**9 + 7
n = len(arr)
arr.sort()
idx = {v: i for i, v in enumerate(arr)}
f = [1] * n
for i, a in enumerate(arr):
for j in range(i):
b = arr[j]
if a % b == 0 and (c := (a // b)) in idx:
f[i] = (f[i] + f[j] * f[idx[c]]) % mod
return sum(f) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to optimize with dynamic programming and hash table lookups.
- question_mark
Understanding of modular arithmetic in large number problems.
- question_mark
Clear explanation of array scanning and the trade-off between time and space complexity.
常见陷阱
外企场景- error
Forgetting to use modulo 10^9 + 7 when calculating the result.
- error
Inefficient solutions due to improper handling of array scanning and hash lookups.
- error
Confusing non-leaf nodes' product with other types of tree structures, leading to incorrect tree construction.
进阶变体
外企场景- arrow_right_alt
Modifying the problem to allow repeated elements in the array.
- arrow_right_alt
Adding constraints where each node can only appear a limited number of times in the tree.
- arrow_right_alt
Changing the rules such that non-leaf nodes' values must not equal the product of their children.