-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreesWithFactors.cpp
More file actions
29 lines (28 loc) · 908 Bytes
/
binaryTreesWithFactors.cpp
File metadata and controls
29 lines (28 loc) · 908 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Source: https://leetcode.com/problems/binary-trees-with-factors/
// Author: Miao Zhang
// Date: 2021-03-15
/*************************************************
* dp[c] = sum(dp[a]*dp[b]), c = a * b
* dp[i] = sum(dp[j] * dp[i/j])
*************************************************/
class Solution {
public:
int numFactoredBinaryTrees(vector<int>& arr) {
int kMod = 1000000007;
std::sort(arr.begin(), arr.end());
unordered_map<int, long> dp;
for (int i = 0; i < arr.size(); i++) {
dp[arr[i]] = 1;
for (int j = 0; j < i; j++) {
if (arr[i] % arr[j] == 0 && dp.count(arr[i] / arr[j])) {
dp[arr[i]] += (dp[arr[j]] * dp[arr[i] /arr[j]]) % kMod;
}
}
}
long res = 0;
for (auto& kv: dp) {
res += kv.second;
}
return res % kMod;
}
};