LeetCode 823. Binary tree with factors (dynamic programming)

Article Directory

1. Title

Given an array containing unique integer elements, each integer is greater than 1.

We use these integers to build a binary tree, and 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 meet the conditions? The returned result should be modulo 10 ** 9 + 7.

示例 1:
输入: A = [2, 4]
输出: 3
解释: 我们可以得到这些二叉树: [2], [4], [4, 2, 2]

示例 2:
输入: A = [2, 4, 5, 10]
输出: 7
解释: 我们可以得到这些二叉树: [2], [4], [5], [10], 
[4, 2, 2], [10, 2, 5], [10, 5, 2].
 
提示:
1 <= A.length <= 1000.
2 <= A[i] <= 10 ^ 9.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/binary-trees-with-factors
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. Problem solving

  • d p [ i ] dp[i] d p [ i ] meansA [i] A[i]A [ i ] is the number of root binary trees
  • A [ i ] > 1 A[i]>1 A[i]>1 The higher the value, the greater the value of the root, sort the array, and hash themap mapm a p record position
  • p = A [ i ] ∗ A [ j ] p= A[i]*A[j] p=A[i]A [ j ] in the array,i ≠ j, dp [map [p]] + = dp [i] ∗ dp [j] ∗ 2 i \neq j, dp[map[p]] += dp[i] *dp[j]*2i=j,dp[map[p]]+=dp[i]dp[j]2. Left and right nodes can be interchanged*2
  • p = A [ i ] ∗ A [ j ] p= A[i]*A[j] p=A[i]A[j] 在数组中, i = j , d p [ m a p [ p ] ] + = d p [ i ] ∗ d p [ j ] i = j, dp[map[p]] += dp[i]*dp[j] i=j,dp[map[p]]+=dp[i]dp[j]
  • The final answer is sum (dp [i])% mod sum(dp[i])\%modsum(dp[i])%mod
class Solution {
    
    
public:
    int numFactoredBinaryTrees(vector<int>& A) {
    
    
    	int n = A.size(), i, j;
    	if(n == 1) return 1;
    	vector<long long> dp(n, 1);
    	sort(A.begin(), A.end());
    	unordered_map<int,int> m;
    	for(i = 0; i < n; i++)
    		m[A[i]] = i;
    	long long ans = 0, p, mod = 1e9+7;
    	for(i = 0; i < n; ++i)
    	{
    
    
    		for(j = 0; j <= i; ++j)
    		{
    
    
    			p = (long long)A[j]*A[i];
    			if(p > int(1e9))
    				break;
    			if(m.find(p) != m.end())
    			{
    
    
                    if(i != j)
                        dp[m[p]] += (2*dp[i]*dp[j])%mod;
                    else
                        dp[m[p]] += (dp[i]*dp[j])%mod;
                }
    		}
    	}
    	for(int i = 0; i < n; i++)
    		ans = (ans+dp[i])%mod;
    	return ans;
    }
};

52 ms 9.5 MB


My CSDN blog address https://michael.blog.csdn.net/

Long press or scan the QR code to follow my official account (Michael Amin), come on together, learn and make progress together!
Michael Amin

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/108680229