算法小练——不同的二叉搜索树


title: 算法小练——不同的二叉搜索树
abbrlink: 4096678489
date: 2020-01-12 21:39:51
categories:
tags:

不同的二叉搜索树

描述

给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?

示例

输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

代码

class Solution {
   public int numTrees(int n) {

        int[] G = new int[n+1];
        G[0] = 1;
        G[1] = 1;
        for (int i = 2; i <=n ;i++) {
            for (int j = 1; j <=i; j++) {
                G[i] += G[j-1]*G[i-j];

            }
        }
        return G[n];

    }
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码2

class Solution {
  public int numTrees(int n) {
    // Note: we should use long here instead of int, otherwise overflow
    long C = 1;
    for (int i = 0; i < n; ++i) {
      C = C * 2 * (2 * i + 1) / (i + 2);
    }
    return (int) C;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

笔记

举例而言,F(3, 7)F(3,7),以 3 为根的不同二叉搜索树个数。为了以 3 为根从序列 [1, 2, 3, 4, 5, 6, 7] 构建二叉搜索树,我们需要从左子序列 [1, 2] 构建左子树,从右子序列 [4, 5, 6, 7] 构建右子树,然后将它们组合(即笛卡尔积)。
巧妙之处在于,我们可以将 [1,2] 构建不同左子树的数量表示为 G(2)G(2), 从 [4, 5, 6, 7]` 构建不同右子树的数量表示为 G(4)G(4)。这是由于 G(n)G(n) 和序列的内容无关,只和序列的长度有关。于是,F(3,7) = G(2) \cdot G(4)F(3,7)=G(2)⋅G(4)。


在这里插入图片描述

发布了98 篇原创文章 · 获赞 105 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_34691097/article/details/103964312