Skip to content

Commit abdcee8

Browse files
authored
Create binary-trees-with-factors.cpp
1 parent a3956f8 commit abdcee8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/binary-trees-with-factors.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int numFactoredBinaryTrees(vector<int>& A) {
7+
static const int M = 1e9 + 7;
8+
sort(A.begin(), A.end());
9+
unordered_map<int, int64_t> dp;
10+
for (int i = 0; i < A.size(); ++i) {
11+
dp[A[i]] = 1;
12+
for (int j = 0; j < i; ++j) {
13+
if (A[i] % A[j] == 0 && dp.count(A[i] / A[j])) {
14+
dp[A[i]] = (dp[A[i]] + dp[A[j]] * dp[A[i] / A[j]]) % M;
15+
}
16+
}
17+
}
18+
return accumulate(dp.cbegin(), dp.cend(), 0L,
19+
[](int64_t x, const pair<int, int>& p) {
20+
return x + p.second;
21+
}) % M;
22+
}
23+
};

0 commit comments

Comments
 (0)