Leetcode Unique Binary Search Trees

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.