您的位置:首页 > 产品设计 > UI/UE

Unique Binary Search Trees

2015-03-21 12:22 246 查看
问题来源:https://leetcode.com/problems/unique-binary-search-trees/

/**
 * 
 * <p>
 * ClassName UniqueBinarySearchTrees
 * </p>
 * <p>
 * Description 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.<br/>
 *   1         3     3      2      1<br/>
 *    \       /     /      / \      \<br/>
 *     3     2     1      1   3      2<br/>
 *    /     /       \                 \<br/>
 *   2     1         2                 3<br/>
 * </p>
 * 
 * @author TKPad wangx89@126.com
 *         <p>
 *         Date 2015年3月20日 下午2:11:23
 *         </p>
 * @version V1.0.0
 *
 *
 */
/**
 * 卡特兰数又称卡塔兰数,英文名Catalan number,是组合数学中一个常出现在各种计数问题中出现的数列。由以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)命名,其前几项为 : 1, 2, 5, 14, 42, 132, 429, 1430,
 * 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020,
 * 91482563640, 343059613650, 1289904147324, 4861946401452
 */
/**
 * 令h(0)=1,h(1)=1,catalan数满足递推式[1] : h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2) 例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
 * h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5 另类递推式[2] : h(n)=h(n-1)*(4*n-2)/(n+1); 递推关系的解为: h(n)=C(2n,n)/(n+1)
 * (n=0,1,2,...) 递推关系的另类解为: h(n)=c(2n,n)-c(2n,n+1)(n=0,1,2,...)
 */
public class UniqueBinarySearchTrees {
    // Time Limit Exceeded
    // public int numTrees(int n) {
    // if (0 == n || 1 == n) {
    // return 1;
    // } else {
    // int sum = 0;
    // for (int i = 0; i <= n - 1; i++) {
    // sum += numTrees(i) * numTrees(n - 1 - i);
    // }
    // return sum;
    // }
    // }
    public int numTrees(int n) {
        if (n <= 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }
        int nums[] = new int[n + 1];
        nums[0] = 1;
        nums[1] = 1;
        nums[2] = 2;
        for (int i = 3; i < nums.length; i++) {
            int temp = 0;
            for (int j = 0; j < i; j++) {
                temp += nums[j] * nums[i - j - 1];
            }
            nums[i] = temp;
        }
        return nums[nums.length - 1];
    }

    public static void main(String[] args) {
        // Last executed input: 19

        // int numTrees = new UniqueBinarySearchTrees().numTrees(0);// 1
        // int numTrees = new UniqueBinarySearchTrees().numTrees(1);// 1
        // int numTrees = new UniqueBinarySearchTrees().numTrees(2);// 1
        int numTrees = new UniqueBinarySearchTrees().numTrees(3);// 1
        // int numTrees = new UniqueBinarySearchTrees().numTrees(6);// 132
        // int numTrees = new UniqueBinarySearchTrees().numTrees(19);
        System.out.println(numTrees);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: