Summary of LeetCode solutions 823. Binary tree with factors

 Directory link:

Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog

GitHub synchronization problem solving project:

https://github.com/September26/java-algorithms

Original title link: LeetCode official website - the technology growth platform loved by geeks around the world


describe:

Given an array containing non-repeating integer elements  arr , each integer  arr[i] is greater than 1.

Use these integers to build a binary tree, each integer can be used any number of times. Among them: the value of each non-leaf node should be equal to the product of the values ​​of its two child nodes.

How many binary trees are there in total that satisfy the condition? The answer may be large, and the remainder of the result is  returned   .109 + 7 

Example 1:

Input:  arr = [2, 4]
Output: 3
 Explanation: These binary trees can be obtained:[2], [4], [4, 2, 2]

Example 2:

Input:  arr = [2, 4, 5, 10]
Output:  7
Explanation: These binary trees can be obtained: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].

hint:

  • 1 <= arr.length <= 1000
  • 2 <= arr[i] <= 109
  • arr All values ​​in  are different from each other

Problem-solving ideas:

Arranged from small to large, the following number must be the product of the previous number. So we first find the possible number of binary trees with previous values ​​and save them. If there is a product of two numbers in the latter value, it is the product of the possible quantities of the first two numbers. If the two numbers are different, you need to multiply by 2 because the left and right positions can be swapped.

Code:

class Solution823
{
public:
    int numFactoredBinaryTrees(vector<int> &arr)
    {
        sort(arr.begin(), arr.end());
        map<int, long long> numMap;
        long long sum = 0;
        int index = 0;
        long long mod = 1e9 + 7;
        while (index < arr.size())
        {
            int i = 0;
            long long num = 1;
            int currentValue = arr[index];
            while (arr[i] <= (currentValue / arr[i]))
            {
                if (currentValue % arr[i] != 0)
                {
                    i++;
                    continue;
                }
                int value = currentValue / arr[i];
                if (numMap.find(value) == numMap.end())
                {
                    i++;
                    continue;
                }
                if (value == arr[i])
                {
                    num = (num + numMap[value] * numMap[value]) % mod;
                }
                else
                {
                    num = (num + (numMap[value] * numMap[arr[i]] * 2)) % mod;
                }
                i++;
            }
            sum = (sum + num) % mod;
            numMap[currentValue] = num;
            index++;
        }
        return sum;
    }
};

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/132568443