Skip to content

Latest commit

 

History

History
44 lines (33 loc) · 1.26 KB

96. Unique Binary Search Trees.md

File metadata and controls

44 lines (33 loc) · 1.26 KB
title toc date tags top
96. Unique Binary Search Trees
false
2017-10-30
Leetcode
Tree
Dynamic Programming
96

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];
}