Topic links: https://leetcode-cn.com/problems/unique-binary-search-trees/
Title Description
Given an integer n, 1 ... n is seeking to nodes of a binary search tree, how many?
Example:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Thinking
First, because the current integer i
when the inevitable situation and <=i
circumstances related to, so we consider the idea of dynamic programming, first establish a one-dimensional dp
array.
dp[i]
He expressed as an integer i
number of binary search tree species composition of the time.
We consider i as the root node, set up sub-tree nodes is left j
, 0<=j<=n-1
then the right child tree nodes i-1-j
. The total number of binary search tree is composed of the combined total of the left subtree and right subtree . That dynamic programming equation.
dp[i] = sum( dp[j] ,dp[i-1-j)) for j in [0,n-1]
The resulting formula is the number of Cattleya
G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)
Complexity Analysis
time complexity: O (n ^ 2)
Complexity Space: O (1)
Code
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1,0);
dp[0] = 1, dp[1] = 1;
for(int i = 2; i<= n; ++i)
for (int j = 0; j <= i-1; ++j)
dp[i] += (dp[j] * dp[i-1-j]);
return dp[n];
}
};