Java for LeetCode 096 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.

解题思路:

二叉查找树,刚上来无从下手,但仔细想想就能发现规律:以i为根节点,i的左子树都是小于i的,共有numTrees(i-1)种情况,i的右子树都是大于i的,共有numTrees(n-i) 种情况,相乘即是以i为根节点的情况,然后依次循环即可,递归下即可解决。当然更高效的方式是采用DP来替代递归,JAVA实现如下:

    public int numTrees(int n) {
        if (n <= 0)
			return 0;
		int[] dp = new int[n + 1];
		dp[0] = 1;
		for (int i = 1; i < dp.length; i++)
			for (int k = 0; k <= i - 1; k++)
				dp[i] += dp[k] * dp[i - k - 1];
		return dp[n];
    }

 

posted @ 2015-05-21 17:35  TonyLuis  阅读(155)  评论(0编辑  收藏  举报