力扣labuladong——一刷day38

本文介绍了两种方法解决LeetCode题目96和95,涉及动态规划求解n个节点的不同二叉搜索树数量,以及使用回溯法生成不同的二叉搜索树。详细讲解了Solution类中的关键代码实现。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言


计算n个节点的BSF数量,与构造n个节点的BFS的全收集

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

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

回溯

class Solution {
    int[][] memo;
    public int numTrees(int n) {
        memo = new int[n+1][n+1];
        return fun(1,n);
    }
    public int fun(int low, int high){
        if(low > high){
            return 1;
        }
        if(memo[low][high] != 0){
            return memo[low][high];
        }
        int res = 0;
        for(int i = low; i <= high; i ++){
            res += fun(low, i-1) * fun(i+1,high);
        }

        memo[low][high] = res;
        return res;
    }
}

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> res = new LinkedList<>();
        if(n == 0){
            return res;
        }
        return fun(1,n);
    }
    public List<TreeNode> fun(int low, int high){
        List<TreeNode> res = new LinkedList<>();
        if(low > high){
            res.add(null);
            return res;
        }
        for(int i = low; i <= high; i ++){
            List<TreeNode> l = fun(low,i-1);
            List<TreeNode> r = fun(i+1,high);
            for(TreeNode tl : l){
                for(TreeNode tr : r){
                    TreeNode cur = new TreeNode(i);
                    cur.left = tl;
                    cur.right = tr;
                    res.add(cur);
                }
            }
        }
        
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

乱世在摸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值