返回介绍

solution / 0000-0099 / 0096.Unique Binary Search Trees / README_EN

发布于 2024-06-17 01:04:05 字数 3842 浏览 0 评论 0 收藏 0

96. Unique Binary Search Trees

中文文档

Description

Given an integer n, return _the number of structurally unique BST's (binary search trees) which has exactly _n_ nodes of unique values from_ 1 _to_ n.

 

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

 

Constraints:

  • 1 <= n <= 19

Solutions

Solution 1: Dynamic Programming

We define $f[i]$ to represent the number of binary search trees that can be generated from $[1, i]$. Initially, $f[0] = 1$, and the answer is $f[n]$.

We can enumerate the number of nodes $i$, then the number of nodes in the left subtree $j \in [0, i - 1]$, and the number of nodes in the right subtree $k = i - j - 1$. The number of combinations of the number of nodes in the left subtree and the right subtree is $f[j] \times f[k]$, so $f[i] = \sum_{j = 0}^{i - 1} f[j] \times f[i - j - 1]$.

Finally, return $f[n]$.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.

class Solution:
  def numTrees(self, n: int) -> int:
    f = [1] + [0] * n
    for i in range(n + 1):
      for j in range(i):
        f[i] += f[j] * f[i - j - 1]
    return f[n]
class Solution {
  public int numTrees(int n) {
    int[] f = new int[n + 1];
    f[0] = 1;
    for (int i = 1; i <= n; ++i) {
      for (int j = 0; j < i; ++j) {
        f[i] += f[j] * f[i - j - 1];
      }
    }
    return f[n];
  }
}
class Solution {
public:
  int numTrees(int n) {
    vector<int> f(n + 1);
    f[0] = 1;
    for (int i = 1; i <= n; ++i) {
      for (int j = 0; j < i; ++j) {
        f[i] += f[j] * f[i - j - 1];
      }
    }
    return f[n];
  }
};
func numTrees(n int) int {
  f := make([]int, n+1)
  f[0] = 1
  for i := 1; i <= n; i++ {
    for j := 0; j < i; j++ {
      f[i] += f[j] * f[i-j-1]
    }
  }
  return f[n]
}
function numTrees(n: number): number {
  const f: number[] = Array(n + 1).fill(0);
  f[0] = 1;
  for (let i = 1; i <= n; ++i) {
    for (let j = 0; j < i; ++j) {
      f[i] += f[j] * f[i - j - 1];
    }
  }
  return f[n];
}
impl Solution {
  pub fn num_trees(n: i32) -> i32 {
    let n = n as usize;
    let mut f = vec![0; n + 1];
    f[0] = 1;
    for i in 1..=n {
      for j in 0..i {
        f[i] += f[j] * f[i - j - 1];
      }
    }
    f[n] as i32
  }
}
public class Solution {
  public int NumTrees(int n) {
    int[] f = new int[n + 1];
    f[0] = 1;
    for (int i = 1; i <= n; ++i) {
      for (int j = 0; j < i; ++j) {
        f[i] += f[j] * f[i - j - 1];
      }
    }
    return f[n];
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文