LeetCode : 96. Unique Binary Search Trees 二叉搜索树数量

试题
Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST’s:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

代码
这一题首先的想法是,以1-n中所有的数作为根节点。因为根节点不同所以可以对数量求和。
当以m为根节点,那么小于m的一定在左子树,大于m的一定在右子树。这样的话我们可以用左子树的方案数*右子树方案数来获得以m为根节点的方案数量。而左子树或右子树的方案数问题又回归到了原问题。另外一个注意点是无需考虑节点数值大小,而只需考虑个数。也就是代码中n-i。
为了降低重复计算,可以使用数组存储。

递归原版:

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

超时优化:

class Solution {
    public int numTrees(int n) {
        int[] mem = new int[n+1];
        mem[0] = 1;
        
        return numTrees(n, mem);
    }
    
    private int numTrees(int n, int[] mem){
        if(mem[n]!=0) return mem[n];
        for(int i=1; i<=n; i++){
            mem[n] += numTrees(i-1, mem) * numTrees(n-i,mem);
        }
        return mem[n];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值