823. Binary Trees With Factors (树上的动态规划)

题意:Given an array of unique integers, each integer 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 it's children.
How many binary trees can we make?  Return the answer modulo 10 ** 9 + 7.
 

 
 
思路: 这道题和一般动态规划题目的形式不太一样,和建树的过程结合起来,但是不要忘记了动态规划的本质是什么,就是有小问题到大问题的转化,可以将大问题分解为小问题,大问题可以由小问题组成,然后看这道题,很明显根节点和子节点是状态转化的关系;
 
回到这题,思考c,c.left=a,c.right=b,以c为根节点能够构造的树的个数, 以c的右子节点为根节点能构造的树的个数,是什么关系?
 
是不是dp[c] = dp[a] * dp[b]呢?因为对于每个a的树形式,和对于每个b的树形式,都是不一样的树;且a、b位交换,也是不一样的树,故正确的状态转移方程应该是:dp[c] = sum{dp[a] * dp[b]}
 
 
 
 
代码:
class Solution {
    public int numFactoredBinaryTrees(int[] A) {
        long res = 0;
        int N = A.length;
        long[] dp = new long[N];
        Arrays.fill(dp, 1);
        Arrays.sort(A);
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < N; i++) {
            map.put(A[i], i);
        }
        int kmod = 1_000_000_007;

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < i; j++) {
                if (A[i] % A[j] == 0) {
                    int right = A[i] / A[j];
                    if (map.containsKey(right)) {
                        dp[i] = (dp[i] + dp[j] * dp[map.get(right)]) % kmod;
                    }
                }
            }
        }
        for (long num : dp) res += num;
        return (int)(res % kmod);
    }
}
View Code

 

或者简化一下,直接用map存也是可以的:

class Solution {
    public int numFactoredBinaryTrees(int[] A) {
        final int kmod = 1_000_000_007;
        Map<Integer, Long> map = new HashMap<>(); //dp[]
        Arrays.sort(A);
        for (int i = 0; i < A.length; i++) {
            map.put(A[i], 1L);
            for (int j = 0; j < i; j++) {
                if (A[i] % A[j] == 0 && map.containsKey((A[i] / A[j]))) {
                    map.put(A[i], (map.get(A[i]) + map.get(A[j]) * map.get(A[i] / A[j])) % kmod);
                }
            }
        }
        long res = 0;
        for (long num : map.values()) res += num;
        return (int) (res % kmod);
    }
}
View Code

 

 
这题还有个坑是注意答案会很大,应该用long型保存,且最后应该求模
 
 

转载于:https://www.cnblogs.com/shawshawwan/p/9558306.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值