LeetCode Unique Binary Search Trees

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangliuy/article/details/48132133

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.

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

思路分析:这题关键在于把握BST的结构特征,从i=0,1,2...逐渐找出递推规律,用count[i]表示有i个节点是BST的数量,那么

i = 0 时 count[i] = 1// 空树

i = 1 时 count[i] = 1//以1为root

i = 2 时 count[i] = count[0]* count[1]//以1为root

                              + count[1]*count[0]//以2为root

i = 3 是 count[i] = count[0]*count[2]//以1为root   都在右子树

                              + count[1]*count[1]//以2为root  左边右边各一个

                              + count[2]*count[0]//以3为root    都在左子树

....

也就是对于 节点1,2,3...i,i+1,...n而言,如果选择i当作root,左边有1,2...i-1,右边有i+1...n。 于是左右子树又划归成了规模较小的已经解决的问题,很容易找到如下递推公式,用DP求解。

count[i] = ∑ count[k] *count [ i-1-k]     0<=k<=i-1

这个就是卡特兰数的一个定义方式。

DP实现,时间复杂度O(n^2),空间复杂度O(n)

AC Code

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

其他参考题解

http://www.programcreek.com/2014/05/leetcode-unique-binary-search-trees-java/

http://blog.csdn.net/linhuanmars/article/details/24761459


猜你喜欢

转载自blog.csdn.net/yangliuy/article/details/48132133