Skip to content

Commit 2122809

Browse files
committed
Add solution #823
1 parent 960406a commit 2122809

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,7 @@
631631
820|[Short Encoding of Words](./0820-short-encoding-of-words.js)|Medium|
632632
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
633633
822|[Card Flipping Game](./0822-card-flipping-game.js)|Medium|
634+
823|[Binary Trees With Factors](./0823-binary-trees-with-factors.js)|Medium|
634635
824|[Goat Latin](./0824-goat-latin.js)|Easy|
635636
827|[Making A Large Island](./0827-making-a-large-island.js)|Hard|
636637
830|[Positions of Large Groups](./0830-positions-of-large-groups.js)|Easy|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 823. Binary Trees With Factors
3+
* https://leetcode.com/problems/binary-trees-with-factors/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
7+
*
8+
* We make a binary tree using these integers, and each number may be used for any number of times.
9+
* Each non-leaf node's value should be equal to the product of the values of its children.
10+
*
11+
* Return the number of binary trees we can make. The answer may be too large so return the answer
12+
* modulo 109 + 7.
13+
*/
14+
15+
/**
16+
* @param {number[]} arr
17+
* @return {number}
18+
*/
19+
var numFactoredBinaryTrees = function(arr) {
20+
const MOD = 1e9 + 7;
21+
const dp = {};
22+
const numMap = new Map();
23+
24+
arr.sort((a, b) => a - b);
25+
for (let i = 0; i < arr.length; i++) {
26+
numMap.set(arr[i], i);
27+
}
28+
29+
let result = 0;
30+
for (let i = 0; i < arr.length; i++) {
31+
dp[arr[i]] = 1;
32+
for (let j = 0; j < i; j++) {
33+
if (arr[i] % arr[j] === 0) {
34+
const complement = arr[i] / arr[j];
35+
if (numMap.has(complement)) {
36+
dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[complement]) % MOD;
37+
}
38+
}
39+
}
40+
result = (result + dp[arr[i]]) % MOD;
41+
}
42+
43+
return result;
44+
};

0 commit comments

Comments
 (0)