Given N, how many structurally unique BST's (binary search trees) that store values 1...N?
For example,
Given n = 3, there is a total of 5 unique BST ' s.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
The main idea is simple, is to calculate how many different two forks looking for a tree to meet the pre-sequence traversal is 1,2,3...N conditions
Idea: Each tree is composed of root node, left subtree, right subtree, once the root node is determined to be X,
Zuozi can only be constituted by 1,2,3...x-1, and the right subtree is composed of X+1,X+2...N, which can
[Method 1] fall generation solution;
classSolution:#@return An integer defnumtrees (self, n): DP= [1, 1, 2] ifN < 3:returnDp[n] DP+ = [0 forIinchRange (n-2)] forIinchRange (3, n+1): forJinchRange (i): Dp[i]+ = Dp[j]*dp[i-j-1] returnDp[n]
[Method 2] Recursive solution
class Solution: # @return an integer def numtrees (self, N): = [1, 1, 2] ifreturn dp[n] = 0 for inch range (N): + = Self.numtrees (i) *self.numtrees (n-i-1 )return ans
[Leetcode] Unique Binary Search Trees @ Python