-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Trees With Factors
More file actions
79 lines (65 loc) · 1.71 KB
/
Copy pathBinary Trees With Factors
File metadata and controls
79 lines (65 loc) · 1.71 KB
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
Using Dynamic Programming & Using Hashing map
1st code:-
Time Complexity is O(N^2)
Space Comolexity is O(N)
#define mod 1000000007
#define ll int long long int
class Solution {
public:
int numFactoredBinaryTrees(vector<int>& arr) {
unordered_map<int,long long int>map;
sort(arr.begin(),arr.end());
for(int i=0;i<size(arr);i++){
map.insert({arr[i],1});
}
for(int i=1;i<size(arr);i++){
long long int count=0;
for(int j=0;j<i;j++){
if(arr[i]%arr[j]==0){
if(map.find(arr[i]/arr[j])!=map.end()){
count+=map.find(arr[j])->second*map.find(arr[i]/arr[j])->second;
}
}
}
map.find(arr[i])->second+=count;
}
long long int sum=0;
for(auto it:map){
sum+=it.second;
}
return sum%mod;
}
};
2nd code:-
#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
int main(){
constexpr int Mod = 1e9 + 7;
int n;
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++){
cin>>arr[i];
}
// Take get the minimum Node to make BT
sort(arr.begin(),arr.end());
// With every one Node can be made BT for sure
vector<long long int>dp(n,1);
unordered_map<int,int>Ind;
for(int i=0;i<n;i++){
Ind[arr[i]]=i;
}
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(arr[i]%arr[j]==0){
int right=arr[i]/arr[j];
if(Ind.count(right)){
dp[i]+=dp[j]*dp[Ind[right]];
dp[i]%=Mod;
}
}
}
}
cout<<accumulate(dp.begin(),dp.end(),0L)<<endl;
}