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

难度:medium

题目:给定整数n,计算有多少种BST结构。

class Solution {
    public int numTrees(int n) {
        long c = 1;
        // Catalan number
        // Catalan (n+1) = (4n+2) / (n+2) Catalan n
        for(int i = 1; i < n; i++){
            c = c * 2 * (2 * i + 1) / (i + 2);
        }
        
        return (int) c;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜