Unique Binary Search Trees——LeetCode

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

题目大意:给定一个数字n,输出它能有多少种表示二叉搜索树的形式。

解题思路:因为是给一个数字n,求它的所有的表示数量,可以简单考虑,设F[n]为n对应的总数。

假设n=4,那么以1为根,形式共有F[0]*F[3],F[0]和F[3]分别对应左右子树的数量;

以2为根,形式共有F[1]*F[2]种;

以3为根,形式共有F[2]*F[1]种;

以4为根,形式共有F[3]*F[0]种;

那么F[4]=F[0]*F[3]+F[1]*F[2]+F[2]*F[1]+F[3]*F[0],由此可以写出代码,由小到大推出来。

    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        Arrays.fill(dp, 0);
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                dp[i] += dp[j - 1] * dp[i - j];
            }
        }
        return dp[n];
    }

 

posted @ 2015-05-01 14:06  丶Blank  阅读(159)  评论(0编辑  收藏  举报