【LeetCode】 96. Unique Binary Search Trees Different binary search trees (Medium) (JAVA)
Subject address: https://leetcode.com/problems/unique-binary-search-trees/
Title description:
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
Topic
Given an integer n, how many types of binary search trees with 1… n as nodes?
Problem solving method
Compared with the previous question, to find all the binary search trees, this question only needs to find out how many types there are: [LeetCode] 95. Unique Binary Search Trees II Different Binary Search Trees II (Medium) (JAVA)
1. Use dynamic programming
2. Find out the dp function, relative to n: 1 ~ n can be the root node, if k is the root node dp[n] = dp[k-1] * dp[n-k]; on the left Possible number of species * possible number of a bit
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}
Execution time: 0 ms, defeated 100.00% of users
in all Java submissions Memory consumption: 36.1 MB, defeated 7.69% of users in all Java submissions