-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_823_BinaryTreeWithFactors.cpp
117 lines (104 loc) · 3.11 KB
/
LC_823_BinaryTreeWithFactors.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
823. Binary Trees With Factors
https://leetcode.com/problems/binary-trees-with-factors/
*/
class Solution {
public:
const int mod = 1e9+7;
int numFactoredBinaryTrees_1(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
int sum=0;
unordered_map<int,long long> hash;
// for(int x: arr)
// hash[x]=1;
for(int i=0; i<n; i++)
{
hash[arr[i]]=1;
// for(int j=i-1; j>=0; j--)
for(int j=0; j<i; j++)
{
int child1 = arr[j];
if(arr[i]%child1==0)
{
int child2 = arr[i]/child1;
if(hash.count(child2))
hash[arr[i]] += hash[child1]*hash[child2];
hash[arr[i]] %= mod;
}
}
sum += hash[arr[i]];
sum %= mod;
}
// for(int i=0; i<n; i++)
// sum = (sum + hash[arr[i]])%mod;
return sum;
}//end
int numFactoredBinaryTrees_2(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
int sum=0;
unordered_map<int,long long> hash;
// for(int x: arr)
// hash[x]=1;
for(int i=0; i<n; i++)
{
long ways =1;
int l = 0;
int r = i-1;
while(l<=r)
{
long child1 = arr[l];
long child2 = arr[r];
long prod = child1*child2;
if(prod < arr[i])
l++;
else if(prod > arr[i])
r--;
else
{
if(l == r)
ways += (hash[child1] * hash[child2])%mod;
else
ways += (2*hash[child1] * hash[child2])%mod;
ways %=mod;
l++;
r--;
}
}
hash[arr[i]] = ways;
sum += ways;
sum %= mod;
}
return sum;
}//end
int numFactoredBinaryTrees(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
int sum=0;
unordered_map<int,long long> hash;
for(int i=0; i<n; i++)
{
long ways =1;
for(int j=0; arr[j]<=sqrt(arr[i]); j++)
{
int child1 = arr[j];
int child2 = arr[i]/child1;
if(arr[i]%child1==0 and hash.count(child2))
{
if(child1 != child2)
ways += (2*hash[child1] * hash[child2])%mod;
else
ways += (hash[child1] * hash[child2])%mod;
ways %= mod;
}
}
hash[arr[i]] = ways;
sum += ways;
sum %= mod;
}
// for(int i=0; i<n; i++)
// sum = (sum + hash[arr[i]])%mod;
return sum;
}//end
};