823. Binary Trees With Factors
Question
Given an array of unique integers, arr
, where each integer arr[i]
is strictly greater than 1
.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node’s value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 1^9 + 7
.
Example 1:
1 | Input: arr = [2,4] |
Example 2:
1 | Input: arr = [2,4,5,10] |
Solution
In this question, it’s easy to find that for each number n, it is a child question which has no connect with what the parent of this number is. So, we can use the memorized dfs to solve this problem.
In addition, for number n, i assume that this number can be devided into arr[i]*arr[j]; So dfs(n) = dfs(arr[i]) * dis(arr[j]). This is because for each legal child tree with arr[i] as the root, it can be combine with each legal child tree with arr[j] as the root. So, i can sort the arr, and find out all arr[i] and arr[j] pairs.
There is a important point, when multiply two ints together and storage it into a long. These to Int number may over the limit. So, to get the right ans, i need to transfer in to long firstly. And that make the multiply.
My solution is as below:
1 | class Solution { |