LeetCode 96. 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.
  1         3     3      2      1
           /     /      /       
     3     2     1      1   3      2
    /     /                        
   2     1         2                 3

思路:

对于一个n个节点的BST, 设F(i,n)是以i为根节点的不同BST个数,G(n)为要求的总数,则G(n)=F(1,n)+F(2,n)+...+F(n,n);

而F(i,n)=G(i-1)*G(n-i), 也即左子树种类数G(i-1),乘以右子树种类数G(n-i); 其中边界情况G(1)=1, 填充一个G(0)=1。

自己想了好久也没想解决方法,一看solution好简单。

本题代码:

/**
 * Created by yuanxu on 17/4/13.
 */
public class DP96 {

    public static int numTrees(int n) {
        int G[] = new int[n+1];
        G[0] = 1;
        G[1] = 1;

        for (int i=2; i<=n; i++) {
            // G[i] = F(1,i) + F(2,i) + ... + F(i,i)
            for (int j=1; j<=i; j++) {
                G[i] += G[j-1] * G[i-j]; // F(j,i) = G[j-1] * G[i-j]
            }
        }
        return G[n];
    }

    /**
     *
     * @test
     */
    public static void main(String args[]) {
        int n = 5;
        System.out.println(numTrees(n));
    }
}

ref: https://leetcode.com/problems/unique-binary-search-trees/#/solutions

原文地址:https://www.cnblogs.com/pinganzi/p/6709867.html