• 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型保存,且最后应该求模
     
     
  • 相关阅读:
    IE浏览器不能启动,双击启动图标无效
    提示Internet Explorer 9 已安装在此系统上,无法完成安装
    React项目跨域处理(两种方案)
    Mock数据模拟Node服务器
    【LeetCode】15. 3Sum
    【C++】int与string互转
    【LeetCode】37. Sudoku Solver
    【LeetCode】149. Max Points on a Line
    【LeetCode】104. Maximum Depth of Binary Tree (2 solutions)
    【LeetCode】140. Word Break II
  • 原文地址:https://www.cnblogs.com/shawshawwan/p/9558306.html
Copyright © 2020-2023  润新知