Leetcode the unique Binary Search trees original problem
Given the number of N of 1 to N, how many two-forked search trees can be formed with each of these shapes.
Note the point:
- This n number is two forks of the search tree node, can not only take part
Example:
Input: n = 3
Output: 5
1 3 3 2 1 \ / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
Thinking of solving problems
First, it is clear that the types of the two-fork search trees that have n unequal numbers are equal. and 1 to n can be used as the root node of the binary search tree, when k is the root node, it has a k-1 on the left, and its right side has n-k of unequal numbers. The type of the two-fork search tree with k as the root node is the product of the possible kinds of the left and right. A recursive representation is where h(n) = h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2) H (0) =h (1) = 1, because 0 or 1 numbers can consist of only one shape. The value of h (x) is calculated from 1 to n in turn. In addition, this is actually a Cattleya number, can be directly calculated using mathematical formula, but the above method is more intuitive.
AC Source
class solution(object): def numtrees(self, n): "" : Type N:int:rtype:int "" "DP = [1 for__inchRange (n +1)] forIinchRange2, n +1): s =0 forJinchRange (i): s + = dp[j] * dp[i-1-j] dp[i] = sreturndp[-1]if__name__ = ="__main__":assertSolution (). Numtrees (5) == the
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Unique Binary Search Trees