forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Trees With Factors.java
44 lines (33 loc) · 1.06 KB
/
Binary Trees With Factors.java
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
class Solution {
int mod = 1000000007;
HashMap<Integer, Long> dp;
HashSet<Integer> set;
public int numFactoredBinaryTrees(int[] arr) {
long ans = 0;
dp = new HashMap<>();
set = new HashSet<>();
for(int val : arr) set.add(val);
for(int val : arr) {
//giving each unique value a chance to be root node of the tree
ans += solve(val, arr);
ans %= mod;
}
return (int)ans;
}
public long solve(int val, int[] nums) {
if(dp.containsKey(val)) {
return dp.get(val);
}
long ans = 1;
for(int i = 0; i < nums.length; i++) {
if(val % nums[i] == 0 && set.contains(val / nums[i])) {
long left = solve(nums[i], nums);
long right = solve(val / nums[i], nums);
ans += ((left * right) % mod);
ans %= mod;
}
}
dp.put(val, ans);
return ans;
}
}