力扣labuladong一刷day36天

力扣labuladong一刷day36天

一、96. 不同的二叉搜索树

题目链接:https://leetcode.cn/problems/unique-binary-search-trees/
思路:这是一道典型的动态规划题,从n=3来看 子树有几种形态 (0, 2)、(1, 1)、(2, 0)有规律可循,即为左子树为0的种数*右子树为2的种数 + 左子树为1的种树 * 右子树为1的种树 + 左子树为2的种数 * 右子树为0的种数。定义dp数组表示dp[i]为n=i时二叉搜索树的种数,递推公式dp[i]=dp[j]*dp[i-j-1] (i<=n, j < i),初始化dp[0]=1, dp[1]=1, dp[2]=2;

class Solution {
     public int numTrees(int n) {
        if (n == 1) return 1;
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                dp[i] += dp[j] * dp[i - j -1];
            }
        }
        return dp[n];
    }
}

二、95. 不同的二叉搜索树 II

题目链接:https://leetcode.cn/problems/unique-binary-search-trees-ii/
思路:

class Solution {


    public List<TreeNode> generateTrees(int n) {
        if (n == 0) return new ArrayList<>();
        return build(1, n);
    }


    List<TreeNode> build(int lo, int hi) {
        List<TreeNode> res = new LinkedList<>();
        // base case
        if (lo > hi) {
            res.add(null);
            return res;
        }

        // 1、穷举 root 节点的所有可能。
        for (int i = lo; i <= hi; i++) {
            // 2、递归构造出左右子树的所有有效 BST。
            List<TreeNode> leftTree = build(lo, i - 1);
            List<TreeNode> rightTree = build(i + 1, hi);
            // 3、给 root 节点穷举所有左右子树的组合。
            for (TreeNode left : leftTree) {
                for (TreeNode right : rightTree) {
                    // i 作为根节点 root 的值
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    res.add(root);
                }
            }
        }

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

当年拼却醉颜红

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值