[LeetCode] Binary Trees With Factors

823. Binary Trees With Factors

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 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int numFactoredBinaryTrees(vector<int>& arr) {
long res = 0;
int MOD = 1e9 + 7;
unordered_map<int, long> dp;
sort(arr.begin(), arr.end());
for(auto& num : arr) {
if(!dp.count(num)) {
long cnt = 1;
for(int i = 2; i * i <= num; i++) {
if(!(num % i) && dp.count(i)) {
cnt += (dp[num/i] * dp[i]) * (i * i == num ? 1 : 2);
}
}
dp[num] = cnt;
}
res = (res + dp[num]) % MOD;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/13/PS/LeetCode/binary-trees-with-factors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.