96. 不同的二叉搜索树(Java)

北战南征 提交于 2020-02-25 00:48:50

1 题目

在这里插入图片描述

2 Java

本题虽然是树的递归,但可以看做动态规划
原因是常规树的递归每个子问题的结果都不一样,无法建立备忘录优化
本题只求个数,[1,2,3]和[2,3,4]两组构成二叉树的数量是一样的,可以建立备忘录优化

2.1 方法一(递归;可看做动态规划)

numi = (num1 * num2)i代表:
i为选定的根节点,0 ~ i-1作为左子树,i+1 ~ n是右子树,且0 ~ i-1构成二叉搜索树数量为num1,i+1 ~ n构成二叉搜索树数量为num2

0 ~ n节点组成的二叉搜索树数量num = num1+num2+num3……nunn

class Solution {
    public int numTrees(int n) {
        if(n == 0 || n == 1)    return 1;
        int ans = 0;
        for(int i = 1; i <= n; i++){
            ans += numTrees(i - 1) * numTrees(n - i);
        }
        return ans;
    }
}

2.2 方法二(优化递归;自顶向下)

带备忘录的递归

class Solution {
    public int numTrees(int n) {
        int[] memory = new int[n + 1];
        return numTrees(n, memory);
    }

    public int numTrees(int n, int[] memory){
        if(n == 0 || n == 1)    return 1;
        if(memory[n] != 0)  return memory[n];

        int ans = 0;
        for(int i = 1; i <= n; i++){
            ans += numTrees(i - 1, memory) * numTrees(n - i, memory);
        }
        memory[n] = ans;
        return ans;
    }
}

2.3 方法三(优化迭代;自底向上动态规划)

带备忘录的迭代

class Solution {
    public int numTrees(int n) {
        int[] memory = new int[n + 1];
        memory[0] = 1;
        memory[1] = 1;

        for(int step = 2; step <= n; step++){
            for(int i = 1; i <= step; i++){
                memory[step] += memory[i - 1] * memory[step - i];
            }
        }
        return memory[n];
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!