leetcode96 Unique Binary Search Trees

题目:

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

思路:

需要使用递推关系来解决。

对于n个结点,除去根节点,还剩余n-1个结点。

因此左右子树的结点数分配方式如下所示:

(0,n-1), (1,n-2), (2, n-3), ....(n-1,0)

我们可以简单的得到:

n=0时,种类数为num(n)=1;

n=1时,种类数为num(n)=1;

则可以依次计算得到n个结点时二叉树的种类。

即:

num(n)=num(0)*num(n-1)+num(1)*num(n-2)+num(2)*num(n-3)+...+num(n-1)*num(0)

代码:

实现时引入了HashMap,方便记录。

    public  int numTrees(int n){
        if( n == 0 || n == 1){
            return 1;
        }
        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
        hm.put(0, 1);
        hm.put(1, 1);
        for(int i = 2; i <= n; i++){
            int num = 0;
            for(int j = 0; j < i; j++){
                num += hm.get(j)*hm.get(i-j-1);
            }
            hm.put(i, num);
        }
        return hm.get(n);
    }

原文地址:https://www.cnblogs.com/bywallance/p/5556904.html