g0001_0100.s0096_unique_binary_search_trees.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0096_unique_binary_search_trees;
// #Medium #Top_100_Liked_Questions #Dynamic_Programming #Math #Tree #Binary_Tree
// #Binary_Search_Tree #Dynamic_Programming_I_Day_11 #Big_O_Time_O(n)_Space_O(1)
// #2022_06_21_Time_0_ms_(100.00%)_Space_40.4_MB_(72.43%)
/**
* 96 - Unique Binary Search Trees\.
*
* Medium
*
* 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:**
*
* ![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg)
*
* **Input:** n = 3
*
* **Output:** 5
*
* **Example 2:**
*
* **Input:** n = 1
*
* **Output:** 1
*
* **Constraints:**
*
* * `1 <= n <= 19`
**/
public class Solution {
public int numTrees(int n) {
long result = 1;
for (int i = 0; i < n; i++) {
result *= 2L * n - i;
result /= i + 1;
}
result /= n + 1;
return (int) result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy