LeetCode刷题笔录Unique Binary Search Trees

50 篇文章 0 订阅
30 篇文章 0 订阅

这题真是想不大明白,上网查了查。发现自己对BST的认识还是不够啊。


这里有个讲解(印度人口音真难懂)。

重点是这个公式:


核心思想是:当k是BST的根节点时,[1,k-1]构成左子树,[k+1,n]构成右子树。根节点确定以后,左子树和右子树的排列是任意的。这样就得到了上面的递归公式。这是一个一维的动态规划,代码很简单。

public class Solution {
    public int numTrees(int n) {
        int[] result = new int[n + 1];
        Arrays.fill(result, 0);
        //when there is no node or only one node, the number of trees is obviously one
        result[0] = 1;
        result[1] = 1;
        for(int i = 2; i <= n; i++){
            for(int j = 1; j <= i; j++){
                result[i] += result[j - 1] * result[i - j];
            }
        }
        return result[n];
    }
}

另外这正是Catalan Number.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值