I won’t say more about the importance of algorithms. If you want to go to a big factory, you have to go through basic knowledge and business logic interview + algorithm interview. Therefore, in order to improve everyone's algorithmic ability, this official account will take you to do an algorithm question every day, and the question will be selected from LeetCode!
The problem I’m talking about today is called different binary search trees . Let’s look at the problem first:
https://leetcode-cn.com/problems/unique-binary-search-trees/
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Title
Given an integer n, how many types of binary search trees with 1...n as nodes?
Sample
Problem solving
Recursive subproblems
Assuming that the number of binary sorted trees in n nodes is G (n), let f(i) be the number of binary search trees rooted at i, then
G(n)=f(1)+f(2)+f(3)+f(4)+...+f(n),
f(i)=G(i−1)∗G(n−i)
class Solution {
public int numTrees(int n) {
if (n == 0 || n == 1) return 1;
int res = 0;
for (int i = 1; i <= n; i++) {
res += numTrees(i - 1) * numTrees(n - i);
}
return res;
}
}
Dynamic programming
From dp[0], dp[1] gradually expand backward
public class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 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];
}
}
Okay, that's all for today's article. If you feel that you have gained something, please read it or forward it. Your support is my biggest motivation.
First half recommendation:
LeetCode50-80 question summary, speed collection!
LeetCode Brush Questions Actual Combat 81: Search Rotating Sort Array II
LeetCode Brush Questions Actual Combat 82: Delete Duplicate Elements in the Sorted List II
LeetCode Practice 83: Remove duplicate elements in the sorted list
LeetCode Brushing Questions in Practice 84: The Largest Rectangle in the Histogram
LeetCode Brush Questions Actual Combat 85: The Largest Rectangle
LeetCode Brush Questions Actual Combat 86: Separate Linked List
LeetCode Brush Questions Actual Combat 87: Disrupting Strings
LeetCode Practice 88: Combine two ordered arrays
LeetCode Practice 89: Gray Code
LeetCode Brush Questions Actual Combat 90: Subset II
LeetCode Practice 91: Decoding Method
LeetCode Brush Questions Actual Combat 92: Reverse Linked List II
LeetCode Practice 93: Recover IP Address
LeetCode Brushing Test 94: In-order traversal of binary tree