0096.不同的二叉搜索树

https://leetcode-cn.com/problems/unique-binary-search-trees

原题

给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。

示例 1:
0096.不同的二叉搜索树 - 图1

  1. 输入:n = 3
  2. 输出:5

示例 2:


输入:n = 1
输出:1

提示:

  • 1 <= n <= 19

标签
树 二叉搜索树 数学 动态规划 二叉树

思路

image.png

卡特兰树

代码

class Solution {
public:
    int numTrees(int n) {
        int dp[21] = {1};
        for(int i = 1; i <= n; i++){
            for(int j = 0; j < i; j++){
                dp[i] += dp[j]*dp[(i-1)-j];
            }
        }
        return dp[n];
    }
};
class Solution {
public:
    int numTrees(int n) {
        return C(2*n, n)/(n+1);
    }
    long long C(int n, int m){ // 组合数 C_{n}^{m}
        long long s = 1;
        for(int i = n, j = 1; j <= m; i--, j++){
            s = s * i / j;
        }
        return s;
    }
};

参考链接:

https://leetcode-cn.com/circle/article/lWYCzv/