跳转至

96. Unique Binary Search Trees

Leetcode Tree Dynamic Programming

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

Example:

Input: 3
Output: 5
Explanation:
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个节点存在二叉搜索树的个数是G(n),可以选取0<i<n为根节点,则0\sim i为左子树,i+1\sim n为右子树。而右子树也可以以这种方式构建。假设选取0<i<n为根节点,则左子树的个数为G(i-1),右子树的的个数为G(n-i),所以以i为根节点的二叉搜索树一共有G(i-1)\times G(n-i)种。最终形成的二叉搜索树一共有\sum_{i=0}^{i=n} G(i-1)\times G(n-i)种。

LeetCode96S

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

    for (int nn = 1; nn <= n; ++nn)
      for (int i = 1; i <= nn; ++i)
        G[nn] += G[i - 1] * G[nn - i];

    return G[n];
}