Unique Binary Search Trees 163

Question

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

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

Solution

思路很简单,就是以某个点i作为根节点时,BST的数目为i左边所有点的BST的个数 * i右边所有点的BST的个数

定义Count[i]为i个数能产生的Unique Binary Tree的数目,

如果数组为空,毫无疑问,只有一种BST,即空树,

Count[0] =1

如果数组仅有一个元素{1},只有一种BST,单个节点

Count[1] = 1

如果数组有两个元素{1,2}, 那么有如下两种可能

Count[2] = Count[0] * Count[1]   (1为根,左边0个数,右边1个数)
        + Count[1] * Count[0]  (2为根,左边1个数,右边0个数)

再看一遍三个元素的数组,可以发现BST的取值方式如下:

Count[3] = Count[0]*Count[2]  (1为根,左边0个数,右边2个数)
           + Count[1]*Count[1]  (2为根,左边1个数,右边1个数)
           + Count[2]*Count[0]  (3为根,左边2个数,右边0个数)

所以,由此观察,可以得出Count的递推公式为

Count[n+1] = ∑ Count[i] * [ n-i]

问题至此划归为一维动态规划。

代码如下:

public class Solution {
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    public int numTrees(int n) {
        // write your code here
        if(n <= 1){
            return 1;
        }

        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;

        for(int i = 2; i <= n; i++){
            for(int j = 0; j < i; j++){
            //Count[n+1] = ∑ Count[i] * [ n-i]
                dp[i] += dp[j] * dp[i - j - 1];
            }
        }

        return dp[n];
    }
}

results matching ""

    No results matching ""